LINQ to objects is my best friend. I am using often the ConvertAll extension method to achieve a conversion.
However I realize I can achieve the same by using the Select extension method.
For example, I have a ListView that displays a list of Alarm objects. I store the object itself in the Tag property of a ListView element. Then I retrieve the selection this way :
Version with ConvertAll:
public Alarm[] SelectedTags
{
get
{
return AlarmListView
.SelectedItems
.OfType<ListViewItem>()
.ToList().ConvertAll(i => i.Tag as Alarm)
.ToArray();
}
}
Version with Select:
public Alarm[] SelectedTags
{
get
{
return AlarmListView
.SelectedItems
.OfType<ListViewItem>()
.Select(i => i.Tag as Alarm)
.ToArray();
}
}
Personally I prefer Select because I can convert my collections easily without having to put them in a List and use ConvertAll. Anyway, both have certainly good reasons to exists.
Is one better than the other ? In which scenarios ?
ConvertAllhas been around since .Net 2.0, whereas LINQ is newer.Selectappears to be more general, and to makeConvertAllredundant.I can’t think of any situation where you would need to use
ConvertAllin new code.Selectis better-known, more general, and works with the other features of LINQ (such as direct translation to SQL queries in LINQ to SQL).