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 );
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.
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.
var indexes = mylist.Select((v, i) => new { v, i })
.Where(x => x.v > 23)
.Select(x => x.i);
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!)
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