1

I have two different types of objects that have ID fields with potentially matching IDs. The FindAll operation returns the correct non-matching objects whereas the Where operation returns all objects. Can someone help me understand why?

var _kenticoIDs = new HashSet<string>(_kenticoSessions.Select(p => p.AttendeeInteractiveSessionID));
var list = _aiSessionIDList.FindAll(p => !_kenticoIDs.Contains(p.SessionID));
var ienum = _aiSessionIDList.Where(p => !_kenticoIDs.Contains(p.SessionID));

EDIT: If I perform a .ToList() on the resultA variable then resulting list is the same as the result variable. However when I inspect the two variables (result/resultA) before the .ToList() one has 6 values and one has 63 values. I feel like I'm missing something obvious.

Jay
  • 624
  • 1
  • 6
  • 19
  • 3
    Your code is *horribly* formatted at the moment, to the point of unreadability. Please fix it. – Jon Skeet Jul 23 '12 at 19:33
  • Are you saying that `_aiSessionIDList.Where(p => !_kenticoIDs.Contains(p.SessionID))` returns every item in `_aiSessionIDList`, even if an item in the list has an ID not in the `_kenticoIDs` hash? – Jaime Torres Jul 23 '12 at 19:36

2 Answers2

5

Where and FindAll are equivalent, except that in terms of execution, Where is deferred, but FindAll is immediate.

Source: This SO thread.

Community
  • 1
  • 1
Channs
  • 2,091
  • 1
  • 15
  • 20
  • I had looked at that exact question earlier and had seen the deferred execution but had mistakenly believed that inspecting it in the debugger was the same as an on-demand operation. – Jay Jul 23 '12 at 19:49
  • Oh ok. Next time, when dealing with LINQ variables, be conscious of the 'deferred' execution context. A good trick is to call the 'Count()' method to force immediate evaluation in the 'Watch' windows. – Channs Jul 23 '12 at 19:54
  • Yeah, I kind of feel like an idiot. It wasn't until I did the ToList() did I realize that I just wasn't doing anything to actually evaluate the resultset. – Jay Jul 23 '12 at 19:58
2

I think the issue you are having is understanding Linq. Where is a Linq extension method whereas FindAll is a List method. Linq expressions are not evaluated until they are enumerated over, or turned into a list/array.

Community
  • 1
  • 1
Jaime Torres
  • 10,365
  • 1
  • 48
  • 56