Difference
between findall() and where() in LINQ
-
S.Nofindall()where()
1 FindAll() is a function on the List type i.e., it can only be used on List instances (or instances of classes that inherit from it, of course). It is not a LINQ extension method like Where().So,if our collection is IEnumerable type, then we cannot use FindAll() as it's a function of List. Where() works on any type that implements IEnumerable 2The 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.)3As findall() creates a list before creating query, hence it is slower than Where()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
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,
we want to find all the records where FirstName = "FirstName1".
To
do this, we 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();
No comments:
Post a Comment