I sometimes use LINQ constructs in my C# source. I use VS 2010 with ReSharper. Now I'm getting "Possible multiple enumeration of IEnumerable" warning from ReSharper.
I would like to refactor it according to the best practices. Here's briefly what it does:
IEnumerable<String> codesMatching = from c in codes where conditions select c;
String theCode = null;
if (codesMatching.Any())
{
theCode = codesMatching.First();
}
if ((theCode == null) || (codesMatching.Count() != 1))
{
throw new Exception("Matching code either not found or is not unique.");
}
// OK - do something with theCode.
A question: Should I first store the result of the LINQ expression in a List? (I'm pretty sure it won't return more than a couple of rows - say 10 at the most.)
Any hints appreciated.
Thanks Pavel
FirsOrDefault
orSingleOrDefault
– vmelnFirstOrDefault()
would miss the case of multiple matches, butSingleOrDefault()
would do the trick. Thanks @VolodymyrMelnychuk – Pavel Foltyn