Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<T> to T item if there is only one element?

Tags:

c#

lambda

I have a List<> with N items. I want to get the first element if and only if N = 1. Can this be done using lambda or some other nice construct?

This works, but looks horrible:

var blah = new List<Object>() { new Object() };
var item = (blah.Count == 1 ? blah[0] : null);
like image 605
l33t Avatar asked Dec 15 '22 21:12

l33t


1 Answers

There are several LINQ extension methods.

  1. SingleOrDefault If there is one element it will be returned, if there are none default<T> will be returned, if there are multiple an exception is thrown
  2. FirstOrDefault If there is one element it will be returned, if there are none default<T> will be returned
  3. ElementAtOrDefault returns the element at the given position or default<T> if the sequence has not so many elements

So for example (my preferred for your requirement):

var item = blah.ElementAtOrDefault(0);

The best method for your requirement depends on how strict this rule is:

I want to get the first element if and only if N = 1.

If it's exceptional that there is more than one element in the sequence, use SingleOrDefault and you'll be informed (error-log) if it gets out of hand.

If it's important that you get the first element and you'll never want another element, use better FirstOrDefault because it has a meaningful name.

If the index of the element in the sequence is important and you (currently) need the first element, but that might change in future, use ElementAtOrDefault.

like image 74
Tim Schmelter Avatar answered Feb 05 '23 14:02

Tim Schmelter