tags:

views:

170

answers:

4

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
this IEnumerable list to make it an extension?
Yuriy Faktorovich
+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
+7  A: 

You want Enumerable.OfType:

list.OfType<MyType>().First();
Jason
+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