One of the principles of LINQ is to be lazy. A LINQ query won’t do any work unless you force the query to do the work. Even when a query does perform work – it does the least amount of work possible. Consider the following code:
int checkCount = 0;
// IEnumerable<Guid> groupIdsToCheckMembership
var groupIdsToCheckMembershipString = groupIdsToCheckMembership.Select(x =>
{
checkCount = checkCount + 1;
return x.ToString();
});
if (checkCount == 0)
{
TraceLogger.LogInformation(this.context, "No Groups in query.");
return new List<Guid>();
}
// continue when there are group membership
This code will alawys return new List()
and the checkCount
will always = 0. Why? Select or Enumerable.Select is defined as “Projects each element of a sequence into a new form by incorporating the element’s index”. Projection is on top of enumerator. For this reason, checkCount = checkCount + 1
was not executed since the array was not enumerating. Once we see the issue, it becomes easy to fix above code. We need to either rewrite Select as loop, or simply force the enumerator to run. For example:
var groupIdsToCheckMembershipString = groupIdsToCheckMembership.Select(x =>
{
checkCount = checkCount + 1;
return x.ToString();
}).ToList();
ToList() converts the IEnumerable to a List object. This forces the enumartor to run along with its projection methods.