Learned something from Resharper: Enumerable.OfType<TResult>

A couple of weeks ago i discovered Enumerable.OfType<TResult> when i let Resharper rewrite my code as a Linq statement. Here is the original code:

var selectedPersons = new List<PersonSelectItem>();
foreach(var selectedItem in selectedItems)
{
 var selectedPerson = selectedItem as PersonSelectItem;
 if (selectedPerson == null) continue;
 selectedPersons.Add(selectedPerson);
}

And here is how it looks after the rewrite:

var selectedPersons = selectedItems.OfType<PersonSelectItem>().ToList();

Yup, the Resharper license was definitely worth it’s money.

This entry was posted on Wednesday, February 17th, 2010 at 19:18 and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply