Brian Hartsock's Blog

Tag: LINQ

LINQ bites back

by bhartsock on Aug.07, 2008, under .NET, Programming

Today I found some odd behavior when working with LINQ. It is hard to describe, so here is the code.

public void Foo(IEnumerable<string> strings)
{
	IEnumberable<string> stringsInDb = strings.Where(s => this.QueryTheDbAndTakeALongTime(s));
 
	foreach(string str in stringsInDb)
	{
		//Where clause in LINQ is actually executed 
	}
 
	foreach(string str in stringsInDb)
	{
		//Where clause in LINQ is actually executed  AGAIN
	}
}

Luckily, some unit tests detected this behavior. It actually isn’t surprising when you think about it though. The proper thing to do for this case is actually call ToList() after the Where().

IEnumberable<string> stringsInDb = strings.Where(s => this.QueryTheDbAndTakeALongTime(s)).ToList();

Don’t let this behavior bite you.

Post to Twitter Post to Digg Post to Facebook Post to Reddit

3 Comments :, , more...

Post by day

March 2010
M T W T F S S
« Jan    
1234567
891011121314
15161718192021
22232425262728
293031