LINQ to Objects: Forced Result Set Evaluation


Usually when using LINQ for querying object collections, evaluation or realisation of the result set is done in the lazy fashion i.e. when actually enumerating the query results. This obviously has its advantages, especially when you consider LINQ to SQL.

However when using LINQ to query object collections or strings it can be useful to force the evaluation of the result set. Why? well something I commonly do, is to use LINQ to process a collection for transformation purposes.

As an example, given a collection of integer ID’s you might like to transform that to a comma seperated string, ordinarilly you’d iterate over the collection like so;

var sb = new StringBuilder();
foreach(var num in numCollection)
{
	sb.AppendFormat("{0},", num);
}
var numColStr = sb.Remove(sb.Length - 1, 1);

Which is all well and good, using LINQ you can do the following;

var sb = new StringBuilder();
numCollection.Select(num => sb.AppendFormat("{0},", num)).Count();
var numColStr = sb.Remove(sb.Length - 1, 1);

Note the use of the .Count() method call at the end of the LINQ query, this causes the result set to be evaluated which in turn causes the select function delegate to be executed, which in this case adds the numbers in the collection to the StringBuilder.  Ok, so what if you need only some of the objects in the collection to be included in the result set and therefore ‘transformed’;

var sb = new StringBuilder();
numCollection.Where(num => num > 10 && num  sb.AppendFormat("{0},", num)).Count();
var numColStr = sb.Remove(sb.Length - 1, 1);

Other extension methods also force the evaluation of the result set, .ToArray() and .ToList() amonst them, however using .Count() iterates the result set and returns the count, while .ToArray() and .ToList() do the same but return an Array and List respectively.

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s