views:

1100

answers:

4

I am prototyping some C# 3 collection filters and came across this. I have a collection of products:

public class MyProduct
    {
        public string Name { get; set; }
        public Double Price { get; set; }
        public string Description { get; set; }
    }

    var MyProducts = new  List<MyProduct>
    {

        new  MyProduct
        {
            Name = "Surfboard",
            Price = 144.99,
            Description = "Most important thing you will ever own."
        },
        new MyProduct
        {
            Name = "Leash",
            Price = 29.28,
            Description = "Keep important things close to you."
        }
        ,
        new MyProduct
        {
            Name = "Sun Screen",
            Price = 15.88,
            Description = "1000 SPF! Who Could ask for more?"
        }
    };

Now if I use LINQ to filter it works as expected:

var d = (from mp in MyProducts
             where mp.Price < 50d
             select mp);

And if I use the Where extension method combined with a Lambda the filter works as well:

var f = MyProducts.Where(mp => mp.Price < 50d).ToList();

Question: What is the difference, and why use one over the other?

+2  A: 

LINQ turns into method calls like the code you have.

In other words, there should be no difference.

However, in your two pieces of code you are not calling .ToList in the first, so the first piece of code will produce an enumerable data source, but if you call .ToList on it, the two should be the same.

Lasse V. Karlsen
A: 

Other than the ToList difference, #2 is a lot more readable and natural IMO

Ricky
+1  A: 

As mentioned d will be IEnumerable<MyProduct> while f is List<MyProduct>

The conversion is done by the C# compiler

var d = 
    from mp in MyProducts
    where mp.Price < 50d
    select mp;

Is converted to (before compilation to IL and with generics expanded):

var d = 
    MyProducts.
    Where<MyProduct>( mp => mp.Price < 50d ).
    Select<MyProduct>( mp => mp ); 
    //note that this last select is optimised out if it makes no change

Note that in this simple case it makes little difference. Where Linq becomes really valuable is in much more complicated loops.

For instance this statement could include group-bys, orders and a few let statements and still be readable in Linq format when the equivalent .Method().Method.Method() would get complicated.

Keith
A: 

The syntax you are using for d will get transformed by the compiler into the same IL as the extension methods. The "SQL-like" syntax is supposed to be a more natural way to represent a LINQ expression (although I personally prefer the extension methods). As has already been pointed out, the first example will return an IEnumerable result while the second example will return a List result due to the call to ToList(). If you remove the ToList() call in the second example, they will both return the same result as Where returns an IEnumerable result.

Scott Dorman