Tuesday, October 5, 2010

DIFFERENCE BETWEEN FINDALL() AND WHERE()

First of all how both these works :
Suppose we have a class Person :

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Now, create an object of person class :
Person person = new Person();

Take a List of person class :
List lstPerson = new List();

Now, assign values to this class and add it to list :
person.FirstName = "FirstName1";
person.LastName = "LastName1";
lstPerson.Add(person);

person.FirstName = "FirstName2";
person.LastName = "LastName2";
lstPerson.Add(person);

Now, I want to find all the records where FirstName = "FirstName1".
To do this, I have two options : FindAll() and Where()

FindAll() :
List result = lstPerson.FindAll(delegate(Person per)
{
return per.FirstName == "Firstname1";
});

Where() :
List result = lstPerson.Where((Person per) => per.FirstName == "FirstName1").ToList();


Both will return the same result. So, the question is which one should be used in which situation?
There are some difference between both, now you have to decide which one suits your requirement:

1. FindAll() is a function on the List type, it's not a LINQ extension method like Where. The LINQ extension methods work on any type that implements IEnumerable, whereas FindAll can only be used on List instances (or instances of classes that inherit from it, of course). If our collection is IEnumerable type, then we can't use FindAll() as it's a function of List.

2. The FindAll method of the List class actually constructs a new list object, and adds results to it. The Where extension method for IEnumerable will simply iterate over an existing list and yield an enumeration of the matching results without creating or adding anything (other than the enumerator itself.)

3. Where is much faster than FindAll. No matter how big the list is, Where takes exactly the same amount of time because Where() just creates a query, It doesn't actually do anything, unlike FindAll which does create a list.


Bookmark and Share

No comments:

Post a Comment