Extending LINQ

When working with LINQ, you’ll probably face the situation where you need to do some calculations behind during a query.

The way you do this is extending System.Collections.IEnumerable. The code blow is an example of how to implement and to use this extension method.

static class LINQExtension
    internal static List GetPrices(this System.Collections.IEnumerable source,
        Func selector = null)
        if (source.Count() == 0)
            return new List();

        if (selector != null)
            source = source.Where(selector);

        var query = from p in source
                    select new Price
                         HighestPrice = p.HighestPrice,
                         LowestPrice = p.LowestPrice

        return query.ToList();

I need to elaborate more this topic, but here’s the utilization:

var prices = from p in products
             select p
                   ProductID = p.ProductID,
                   CategoryID = p.CategoryID,
                   Name = p.Name,

                   Prices = products.GetPricesPerStore(x => x.ProductID == p.ProductID)

return prices.ToList();


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s