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});

      

+2


source to share


7 replies


The difference (if you want to be legible) is that the former is LINQ and the latter is not.



LINQ is the integrated query language that you see in the first example, and the compiler turns it into using the extension methods discussed in the second example.

+1


source


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.



+25


source


There is no real difference. The first, where (and select), is a special language expression that is translated by the compiler into these other lambda-based Where and Select methods.

+6


source


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.

+5


source


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.

+2


source


I believe they are identical. Microsoft created the syntax in (1) for readability, but the compiler treats it like (2).

+2


source


There are some additional functionality in the in.where () method, for example. you can use method index extension.

But for this example, it's just readable.

-1


source







All Articles