Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding first index of element that matches a condition using LINQ

Tags:

c#

linq

var item = list.Where(t => somecondition); 

I would love to be able to find out the index of the element that was returned, in fact, in my case all I want is an index, so that I can .Skip() into the list by that much.

Is there a way to do this in an IEnumerable? I'd hate to use a List<T> for this, but that does have a FindIndex() method

like image 423
user494352 Avatar asked Nov 02 '10 06:11

user494352


People also ask

How do you find the index of an element in LINQ?

LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.

What is use of first () in LINQ?

C# Linq First() Method Use 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.

Which function will return the first occurrence of specified element in a list?

Find(Predicate<T>) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the first occurrence of that element within the entire List<T>.

How do I get first or default in LINQ?

Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection.


1 Answers

If you really just need the first index then count the ones that don't match:

var index = list.TakeWhile(t => !someCondition).Count() 
like image 83
Gareth Avatar answered Sep 23 '22 17:09

Gareth