10 Aug 2011

Linq select vs Enumerable.Select()

I found the MSDN docs a bit confusing with this, so here's a brief aide memoire about how to transform a list of one Type to a list of another, using Linq and also Enumerable Linq methods.

In this case I'm transforming from a List of EF Entities (called promotions here) to a list of MVC SelectListItems.

Standard Linq stylee

var query = from promo in promotions
select new SelectListItem { Text = promo.Name, Value = promo.Id.ToString() };

Enumerable Linq Method stylee


var query = promotions.Select(promo => new SelectListItem() { Text = promo.Name, Value = promo.Id.ToString() });

To get a List out, you just do query.ToList().

No comments:

Post a Comment

Comments are very welcome unless you're a spammer, in which case you should probably kill yourself.

If I helped you out today, you can buy me a beer below. Cheers!