如何将foreach循环转换为Linq查询?

Chr*_*isP 3 c# linq

具有以下结构

[[1,10],[2,20],[5,45],[10,34]]
Run Code Online (Sandbox Code Playgroud)

这个foreach循环找到匹配"planYear"的第一个元素.如果planYear = 5,则将选择第三个元素值"45".

List<object> gifts = gifts;
foreach (List<object> item in gifts)
{
  if (item[0] == planYear)
  {
    gift = Convert.ToDouble(item[1]);
    break;
  }
}
Run Code Online (Sandbox Code Playgroud)

什么是类似的Linq声明来实现同样的结果?

Dan*_*rth 8

var gift = gifts.Cast<List<object>>()
                .Where(x => x[0] == planYear)
                .Select(x => Convert.ToDouble(x[1]))
                .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

If no matching entry has been found gift will be 0. If that's not what you want, use First() instead. 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>. If even one item is of a different type, this code will throw an InvalidCastException. If this is a problem, use OfType instead of Cast.