Finding first index of element that matches a condition using LINQ

前端 未结 7 2074
闹比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:18

    In reference to Jon Skeet's answer, you can use DefaultIfEmpty() before calling FirstOrDefault without adding and subtracting from the index.

       var index = list.Select((value, index) => new { value, index })
                    .Where(pair => SomeCondition(pair.value))
                    .Select(pair => pair.index).DefaultIfEmpty(-1)
                    .FirstOrDefault();
    

提交回复
热议问题