简体   繁体   中英

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". If planYear=5 then the third element value of "45" would be selected.

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?

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 . 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 .

var gift = Convert.ToDouble(
               gifts.Cast<List<object>>().First(x => x[0] == planYear)[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM