What would be the shortest notation to find the first item that is of a certain type in a list of elements using LINQ and C#.
+11
A:
Use the OfType extension method:
public static T FindFirstOfType<T>(IEnumerable list){
return list.OfType<T>().FirstOrDefault();
}
Akselsson
2009-08-24 14:04:18
this IEnumerable list to make it an extension?
Yuriy Faktorovich
2009-08-24 18:15:37
+5
A:
var first = yourCollection.OfType<YourType>().First();
Note that the First method will throw an exception if there are no elements of type YourType. If you don't want that then you could use FirstOrDefault or Take(1) instead, depending on the behaviour you do want.
LukeH
2009-08-24 14:04:51
+3
A:
You could just use the FirstOrDefault and pass in the delegate to use for the comparison.
object[] list = new object[] {
4,
"something",
3,
false,
"other"
};
string first = list.FirstOrDefault(o => o is string); //something
Hugoware
2009-08-24 14:32:58