[ACCEPTED]-Find first element of certain type in a list using LINQ-linq

Accepted answer
Score: 37
var first = yourCollection.OfType<YourType>().First();

Note that the First method will throw an exception 3 if there are no elements of type YourType. If you 2 don't want that then you could use FirstOrDefault or Take(1) instead, depending 1 on the behaviour you do want.

Score: 14

Use the OfType extension method:

public static T FindFirstOfType<T>(IEnumerable list){
 return list.OfType<T>().FirstOrDefault();
}

0

Score: 8

You want Enumerable.OfType:

list.OfType<MyType>().First();

0

Score: 5

You could just use the FirstOrDefault and pass in the 1 delegate to use for the comparison.

object[] list = new object[] {
    4,
    "something",
    3,
    false,
    "other"
};

string first = list.FirstOrDefault(o => o is string); //something

More Related questions