Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first element of certain type in a list using LINQ

Tags:

c#

linq

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#.

like image 974
bitbonk Avatar asked Aug 24 '09 14:08

bitbonk


People also ask

How to get the first element in LINQ c#?

C# Linq First() MethodUse the First() method to get the first element from an array. Firstly, set an array. int[] arr = {20, 40, 60, 80 , 100}; Now, use the Queryable First() method to return the first element.

How do I get the first item in a list?

Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

How do you get the second element in a list?

Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.


4 Answers

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.

like image 135
LukeH Avatar answered Oct 07 '22 16:10

LukeH


Use the OfType extension method:

public static T FindFirstOfType<T>(IEnumerable list){
 return list.OfType<T>().FirstOrDefault();
}
like image 38
Akselsson Avatar answered Oct 07 '22 16:10

Akselsson


You want Enumerable.OfType:

list.OfType<MyType>().First();
like image 29
jason Avatar answered Oct 07 '22 17:10

jason


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
like image 23
hugoware Avatar answered Oct 07 '22 18:10

hugoware