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#.
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.
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.
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.
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.
Use the OfType extension method:
public static T FindFirstOfType<T>(IEnumerable list){
return list.OfType<T>().FirstOrDefault();
}
You want Enumerable.OfType
:
list.OfType<MyType>().First();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With