简体   繁体   English

如何获取列表中为空的每个项目的索引 <T> 通过Linq

[英]How to get the index of each item that is null in a List<T> via Linq

Is there a way to get the index of each object in a List that is null? 有没有一种方法可以获取列表中为空的每个对象的索引?

For example: 例如:

List<string> list = new List<string>() { "1", null, "2", null, "3" };

Is it possible to get the information that list[1] and list[3] is null? 是否可以获得list [1]和list [3]为空的信息? In the best case I would get another list that provides me all the indexes that are null. 在最佳情况下,我将获得另一个列表,该列表为我提供所有为空的索引。

Yes, the simplest option would probably be: 是的,最简单的选择可能是:

var nullIndexes = list.Select((value, index) => new { value, index })
                      .Where(pair => pair.value == null)
                      .Select(pair => pair.index)
                      .ToList();

Try this. 尝试这个。

list.Select((item,i) => new { index = i, item=item })
    .Where(p=>p.item == null)
    .Select(item=>item.index);

Working Demo 工作Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM