Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select single item from a list

Tags:

Using LINQ what is the best way to select a single item from a list if the item may not exists in the list?

I have come up with two solutions, neither of which I like. I use a where clause to select the list of items (which I know will only be one), I can then check the count and make a Single call on this list if count is one, the other choice is to use a foreach and just break after getting the item.

Neither of these seem like a good approach, is there a better way?

like image 788
Daniel Avatar asked Apr 09 '09 17:04

Daniel


People also ask

How to get single item from list in c#?

You can use IEnumerable. First() or IEnumerable. FirstOrDefault() . The difference is that First() will throw if no element is found (or if no element matches the conditions, if you use the conditions).


2 Answers

You can use IEnumerable.First() or IEnumerable.FirstOrDefault().

The difference is that First() will throw if no element is found (or if no element matches the conditions, if you use the conditions). FirstOrDefault() will return default(T) (null if it's a reference type).

like image 168
Reed Copsey Avatar answered Sep 18 '22 09:09

Reed Copsey


Use the FirstOrDefault selector.

var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  var firstEven = list.FirstOrDefault(n => n % 2 == 0);  if (firstEven == 0)     Console.WriteLine("no even number"); else      Console.WriteLine("first even number is {0}", firstEven); 

Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.

If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.

Hope this helps :-)

like image 33
chakrit Avatar answered Sep 22 '22 09:09

chakrit