If I have an IEnumerable object in my .net code that contains a single element, what is the best way to convert the IEnumerable to a single object while checking that the IEnumerable does, indeed, contain only one element?
Here are a couple of ideas that come to mind:
IEnumerable<string> strings = getStrings();
if (string.Count() != 0 ) throw new Exception();
else return strings.First();
return getStrings().Single(x => true);
If your goal is to raise an exception anyways, you can just use:
This will automatically raise an
InvalidOperationExceptionif there is more than one string in the enumeration.