[英]How to convert foreach loop to a Linq query?
With the following structure 具有以下结构
[[1,10],[2,20],[5,45],[10,34]]
this foreach loop finds the first element that matches "planYear". 这个foreach循环找到匹配“planYear”的第一个元素。 If planYear=5 then the third element value of "45" would be selected. 如果planYear = 5,则将选择第三个元素值“45”。
List<object> gifts = gifts;
foreach (List<object> item in gifts)
{
if (item[0] == planYear)
{
gift = Convert.ToDouble(item[1]);
break;
}
}
What would be an analogous Linq statement to achieve this same result? 什么是类似的Linq声明来实现同样的结果?
var gift = gifts.Cast<List<object>>()
.Where(x => x[0] == planYear)
.Select(x => Convert.ToDouble(x[1]))
.FirstOrDefault();
If no matching entry has been found gift
will be 0
. 如果未找到匹配的条目,则gift
将为0
。 If that's not what you want, use First()
instead. 如果那不是您想要的,请改用First()
。 This will throw an exception if no matching item exists. 如果不存在匹配项,则会抛出异常。
This answer assumes - just like your foreach
loop - that every item inside gifts
is actually a List<object>
. 这个答案假设 - 就像你的foreach
循环一样 - gifts
中的每个项目实际上都是List<object>
。 If even one item is of a different type, this code will throw an InvalidCastException
. 如果一个项目的类型不同,则此代码将抛出InvalidCastException
。 If this is a problem, use OfType
instead of Cast
. 如果这是一个问题,请使用OfType
而不是Cast
。
var gift = Convert.ToDouble(
gifts.Cast<List<object>>().First(x => x[0] == planYear)[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.