LINQ bites back

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. »