Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use an extension method with lambda over LINQtoObjects to filter a collection?

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?

like image 720
KP. Avatar asked Aug 07 '08 19:08

KP.


2 Answers

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.

like image 147
Lasse V. Karlsen Avatar answered Sep 22 '22 11:09

Lasse V. Karlsen


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.

like image 22
Keith Avatar answered Sep 20 '22 11:09

Keith