[ACCEPTED]-Find first element of certain type in a list using LINQ-linq
Accepted answer
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.
Use the OfType extension method:
public static T FindFirstOfType<T>(IEnumerable list){
return list.OfType<T>().FirstOrDefault();
}
0
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
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.