Find indices of particular items in the list using linq

后端 未结 2 613
天命终不由人
天命终不由人 2020-12-07 04:01

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

相关标签:
2条回答
  • 2020-12-07 04:19

    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
    0 讨论(0)
  • 2020-12-07 04:35
        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);
    
    0 讨论(0)
提交回复
热议问题