ChrisP
ChrisP

Reputation: 10116

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?

Upvotes: 3

Views: 959

Answers (2)

Tim S.
Tim S.

Reputation: 56536

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

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174279

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.

Upvotes: 8

Related Questions