Find indices of specific elements in a list using linq

I have a list of integers from 1 to 20. I want indexes of elements that are greater than 10 using linq. Is this possible with linq?

Thanks in advance

+3
source share
2 answers

Use overload Selectthat includes an index:

var highIndexes = list.Select((value, index) => new { value, index })
                      .Where(z => z.value > 10)
                      .Select(z => z.index);

Steps in turn:

  • Project a sequence of values ​​into a sequence of pairs of values ​​/ indices
  • Filter only pairs with a value greater than 10
  • Project the result onto a sequence of indices
+8
source
    public static List<int> FindIndexAll(this List<int> src, Predicate<int> value)
    {
        List<int> res = new List<int>();
        var idx = src.FindIndex(x=>x>10);           
        if (idx!=-1) {
        res.Add(idx);
         while (true)
         {
            idx = src.FindIndex(idx+1, x => x > 10);
            if (idx == -1)
                break;
            res.Add(idx);
         }
        }
        return res;
    }

Using

        List<int>  test= new List<int>() {1,10,5,2334,34,45,4,4,11};
        var t = test.FindIndexAll(x => x > 10);
+1
source

Source: https://habr.com/ru/post/1778903/


All Articles