linq的三元运营商 [英] Terniary operator in linq

查看:87
本文介绍了linq的三元运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个三元运算符where where子句linq。



我尝试过:



I need a ternary operator in where clause linq.

What I have tried:

filteredItem = ItemList.Where(x =>; (Model != "" ? (x.ModelNumber.ToLower().Contains(Model.ToLower())) : x.ModelNumber)

推荐答案

在三元运算符中,每一侧的两个元素都必须返回相同的类型。

在你的代码中显然不是这种情况,左边的部分返回一个布尔值(包含方法),而右边的部分似乎返回一个字符串(ModelNumber)。



请参阅? :运算符(C#参考) [ ^ ]。

特别是本段:

In a ternary operator, both elements in each side of the : must return the same type.
Which is apparently not the case in your code, where the left part returns a boolean (Contains method) whereas the right part seems to return a string (ModelNumber).

Please see ?: Operator (C# Reference)[^].
Especially this paragraph:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.





希望这会有所帮助。



Hope this helps.


这没有任何意义。



您发布的代码执行此操作:

That doesn't make any sense.

The code you posted does this:
if Model does not equal ""
    // This will return a boolean value.
    return (x.ModelNumber.ToLower().Contains(Model.ToLower())
else
    // This will return whatever ModelNumber is.
    return x.ModelNumber



我非常怀疑你的ModelNumber是一个布尔值,所以你的两个返回类型是不同的。在三元操作中,这是一个灾难的处方。


I highly doubt your ModelNumber is a boolean so your two return types are different. In a Ternary operation, that is a recipe for disaster.


从您的代码我猜你正在尝试同时过滤和修改你的代码,这通常是不可能的开箱即用。



如果我正确理解你的片段,你想要返回一个ModelNumber属性,如果Model不是空的并且它当前包含它迭代元素。



这是一个可能的解决方案:



From your code I am guessing that you are trying to filter and modify your code at the same time, which usually is not possible to do out of the box.

If I understood you snippet correctly you want to return a "ModelNumber" property if "Model" is not empty and it is contained it currently iterated element.

Here is a possible solution:

var filteredItems =
                string.IsNullOrWhiteSpace(Model)
                    ? ItemList
                    : ItemList.Where(x => x.ModelNumber.ToLowerInvariant().Contains(Model.ToLowerInvariant())).ToList();





希望这会有所帮助,祝你好运,下次请尝试更具体,或向我们展示更多代码。



干杯!



Hope this helps, good luck and next time please try to be more specific, or show us more code.

Cheers!


这篇关于linq的三元运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆