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

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

This works, but it looks awful:

 var blah = new List<Object>() { new Object() }; var item = (blah.Count == 1 ? blah[0] : null); 
+4
source share
5 answers

There are several LINQ extension methods.

  • SingleOrDefault If there is one element, it will be returned if no default<T> is returned, if several exceptions are thrown.
  • FirstOrDefault If there is one element, it will be returned if default<T> not returned
  • ElementAtOrDefault returns an element at a given position or default<T> if there are not many elements in the sequence

So for example (my preferred one for your requirement):

 var item = blah.ElementAtOrDefault(0); 

The best way 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 is exceptional that the sequence contains more than one element, use SingleOrDefault and you will be informed (error log) if it gets out of control.

If it is important that you get the first item and you never need another item, use FirstOrDefault better, because it has a meaningful name.

If the index of an element in a sequence is important and you (currently) need the first element, but this may change in the future, use ElementAtOrDefault .

+7
source

You can write your extension method for it:

 public static class ListExtensions { public static T SingleOrNothing<T>(this IList<T> list) where T : class { if (list.Count == 1) return list.Single(); else return null; } } 

Then you just call it in your code as such:

 var item = someList.SingleOrNothing(); 
+4
source

I think SingleOrDefault is what you are looking for:

 using System.Linq; ... var item = blah.SingleOrDefault(); 
+1
source

This doesn't look much better, but you can use blah.Single() instead of blah[0] :

 var blah = new List<Object>() { new Object() }; var item = blah.Count == 1 ? blah.Single() : null; 
0
source

if you have:

 var blah = new List<MyClass>() { new MyClass() }; 

You can do it:

 var item = (blah.Count == 1 ? blah[0].Single<MyClass>() : null); 
0
source

All Articles