Finding first index of element that matches a condition using LINQ

前端 未结 7 2054
闹比i
闹比i 2021-01-01 08:25
var item = list.Where(t => somecondition);

I would love to be able to find out the index of the element that was returned, in fact, in my case a

7条回答
  •  甜味超标
    2021-01-01 09:20

    Ofcourse its possible using IEnumerable...

     public static class EnumerableExtension
        {
    
            public static int FirstIndexMatch(this IEnumerable items, Func matchCondition)
            {
                var index = 0;
                foreach (var item in items)
                {
                    if(matchCondition.Invoke(item))
                    {
                        return index;
                    }
                    index++;
                }
                return -1;
            }
        }
    

提交回复
热议问题