Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the indices of items fulfilling some condition in List of int?

Tags:

c#

list

indexing

I have a list of int containing items { 10, 11, 23, 34, 56, 43 } and I want to find out the indices of all items which are greater than 23. These values can be any order so I do not want to sort them.

List<int> mylist = new List<int> { 10, 11, 23, 34, 56, 43 };

I am interested in indices of all items those are fulfilling the condition and not only first item which fulfill condition. so this line of code is not working for me.

int index = mylist.FindIndex( x => x > 23 );
like image 347
User1551892 Avatar asked Jan 23 '13 09:01

User1551892


People also ask

How do you find all indices of an element in a list?

NumPy makes the process of finding all index positions of an element in a list very easy and fast. This can be done by using the where() function. The where() function returns the index positions of all items in an array that match a given value.

How do you find the index of list elements that meet a condition in Python?

In Python to find a position of an element in a list using the index() method and it will search an element in the given list and return its index.


2 Answers

var indexes = mylist.Select((v, i) => new { v, i })
                    .Where(x => x.v > 23)
                    .Select(x => x.i);
like image 187
rgripper Avatar answered Oct 12 '22 12:10

rgripper


Linq doesn't provide such a thing directly, but you could write your own. Something like this:

public static IEnumerable<int> FindIndices<T>(this IEnumerable<T> items, Func<T, bool> predicate) 
{
    int i = 0;

    foreach (var item in items) 
    {
        if (predicate(item)) 
        {
            yield return i;
        }

        i++;
    }
}

Then something like:

foreach (int index in mylist.FindIndices( x => x > 23 ))
    ...

(This has the advantage of being more efficient than the other approaches listed above. This is only significant for LARGE sequences though!)

like image 26
Matthew Watson Avatar answered Oct 12 '22 13:10

Matthew Watson