3

I have a list of integers from 1 to 20. I want the indices of items which are greater than 10 using linq. Is it possible to do with linq?

Thanks in advance

nawfal
  • 70,104
  • 56
  • 326
  • 368
ratty
  • 13,216
  • 29
  • 75
  • 108

2 Answers2

9

Use the overload of Select which includes the index:

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

The steps in turn:

  • Project the sequence of values into a sequence of value/index pairs
  • Filter to only include pairs where the value is greater than 10
  • Project the result to a sequence of indexes
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1
    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;
    }

Usage

        List<int>  test= new List<int>() {1,10,5,2334,34,45,4,4,11};
        var t = test.FindIndexAll(x => x > 10);
RameshVel
  • 64,778
  • 30
  • 169
  • 213
  • 1
    This looks a pretty complicated way of going about it. If I wasn't going to use LINQ, I'd probably just loop through myself. Note that your code will currently fail if there are *no* entries matching the predicate - it will put -1 in the list. – Jon Skeet Dec 07 '10 at 08:20
  • @ramesh thank you for your reply by the by i am also chennai guy – ratty Dec 07 '10 at 09:00
  • @ramesh give your mail id if u like if i have any doubt i will conduct through that – ratty Dec 07 '10 at 09:21
  • @ratty, you can get better answers here in SO than from me. :) my id is raam_kimi at hot mail dot com... – RameshVel Dec 07 '10 at 09:40