Convert <T> list to T element if there is only one element?
There are several LINQ extension methods.
SingleOrDefaultIf there is one element, it will be returned if nodefault<T>is returned, if several exceptions are thrown.FirstOrDefaultIf there is one element, it will be returned ifdefault<T>not returnedElementAtOrDefaultreturns an element at a given position ordefault<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 .
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();