What is the difference between LINQ query expressions and extension methods

后端 未结 8 1073
一个人的身影
一个人的身影 2020-12-23 15:39

Below are two queries that return the same data. Other then style I am not sure which is better.

What factors influence these queries? What are the benefits of us

8条回答
  •  一个人的身影
    2020-12-23 15:54

    The where clause in the first example is actually just syntactic sugar for the Where clause in your second method. In fact, you can write your own class that has nothing to do with Linq or IQueryable and just by having a Where method, you can use that syntactic sugar. For example:

        public class MyClass
        {
    
            public MyClass Where(Func predicate)
            {
                return new MyClass { StringProp = "Hello World" };
            }
    
            public MyClass Select(Func predicate)
            {
                return new MyClass ();
            }
    
    
    
            public string StringProp { get; set; }
        }
    

    This is obviously a stupid example, but note that there's a Where method that just returns a new MyClass with stringprop set to Hello World. To demonstrate:

    MyClass a = new MyClass();
                var q = from p in a
                        where p.StringProp == "foo" // doesnt matter what we put here, as we're not really checking the predicate
                        select p;
                Console.WriteLine(q.StringProp);
    

    This will result in writing out "Hello World". Again, this example is obviously pointless, but it proves the point that the "where" syntax just looks for a Where method in your code that takes a Func.

提交回复
热议问题