Difference between two "where" in LINQ
Please let me know the difference between "where" in (1) and "where ()" in (2).
When to use "where" and "where ()"?
List<Person> pList =
new List<Person>
{
new Person
{EmpNo=1,FirstName="Marc",LastName="Loel",Salary=3434},
new Person
{EmpNo=2, FirstName="Steve",LastName="Kaith",Salary=4545},
new Person
{EmpNo=3,FirstName="Neol",LastName="Henk",Salary=2222},
};
(1) var v = from p in pList where p.EmpNo == 1 select new { p.FirstName };
(2) var query =pList .Where(p => p.EmpNo == 1)
.Select(p => new { p.FirstName});
source to share
The difference is that one form is easier to read and the other is harder to read. The problem is that about half of the people think the first one is simpler, and half of the people think the second one is easier! Pick the one you like best and stick with it; they mean the same thing.
source to share
It's just syntactic sugar. In fact, if you have a class with the correct Where method, even if the class is not enumerable, you can use syntactic magic:
class MyClass
{
public IQueryable<int> Where(Func<int, bool> predicate)
{
return Enumerable.Range(1, 100).AsQueryable();
}
}
static void Main(string[] args)
{
var q = from p in new MyClass()
where p == 10
select p;
}
It doesn't do anything, but it builds and calls this method.
source to share
There is no difference. Number (1) is simply written with syntactic sugar.
A quick look at the code in the reflector and it looks like this:
var v = pList.Where<Person>(delegate (Person p) {
return (p.EmpNo == 1);
}).Select(delegate (Person p) {
return new { FirstName = p.FirstName };
});
var query = pList.Where<Person>(delegate (Person p) {
return (p.EmpNo == 1);
}).Select(delegate (Person p) {
return new { FirstName = p.FirstName };
});
As you can see, they are exactly the same.
source to share