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...

Retrieving DropDownList Values in Razor or C#

Recently I needed to update the value of an Umbraco DropDownList property in code based on a value instead of the key that's automatically assigned by the Prevalue Editor.  I came across this but it discusses retrieving values for XSLT specifically.  In my scenario I needed to find a specific key.

The simplest way to do this is with XML to Linq.  In the example below I'm using the property's DataTypeDefinition to retrieve the relevant prevalue collection instead of hard-coding the Id of the DropDownList.  This means I have full flexibility in case something changes in the future:

if (p.getProperty("status") != null)
{
    var status = p.getProperty("status");

    status.Value = XElement.Parse(library.GetPreValues(status.PropertyType.DataTypeDefinition.Id).Current.OuterXml)
                           .Descendants("preValue").FirstOrDefault(pv => pv.Value == "On Offer").Attribute("id").Value;

    p.Save();
}

Note I could also have written it like this in Linq notation:

status.Value = (from pv in XElement.Parse(library.GetPreValues(status.PropertyType.DataTypeDefinition.Id).Current.OuterXml).Descendants("preValue")
                       where pv.Value == "On Offer"
                       select pv.Attribute("id").Value).FirstOrDefault();

 That's all there is to it.