Quantcast
Viewing all articles
Browse latest Browse all 10

Reply: How not to use Linq

Recently (well, today) the CodeProject Insider featured a blog entry - How not to use Linq.  It was a short but interesting artile that prompted me to write a comment but alas no comments can be written on the site.  So I thought I'd better answer it here instead.  Go have a read if you haven't already done so...

While I appreciate the intent and points of the article, I think it's also important to note the benefits of .Select() and .FirstOrDefault() as they have a place when used well.

With the former, it allows one to transform the results into another kind of object or even an anonymous object if required.  With the latter, the second form of the extension method is very powerful in that you can supply an object to use as the default if there are no results from the query.

So for example:

var product = products
     .Where(p => p.Id == 42)
    .Select(p => new SelectListItem{ Value = p.Id, Text = p.Name });

will produce an IEnumerable<SelectListItem> that can be used for example to populate a Select List in ASP.Net MVC templates.

var product = products
     .Where(p => p.Id == 42)
    .FirstOrDefault(new Product());

could be used to return a default product instance instead of a null.

var id = products
     .Where(p => p.Available)
     .Select(p => p.Id)
    .FirstOrDefault(-1);

would either return -1 if no available products are found, or the first product Id.

Very powerful stuff ths Linq with Extension Methods...

Any comments? Feel free to post your views on this topic...

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles