Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# linq possible multiple enumeration best practices

Tags:

c#

linq

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

like image 509
Pavel Foltyn Avatar asked Dec 14 '25 00:12

Pavel Foltyn


1 Answers

Since you want to verify if your condition is unique, you can try this (and yes, you must store the result):

var codes = (from c in codes where conditions select c).Take(2).ToArray();
if (codes.Length != 1)
{
  throw new Exception("Matching code either not found or is not unique.");
}

var code = codes[0];
like image 128
João Simões Avatar answered Dec 15 '25 13:12

João Simões



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!