【问题标题】:LINQ select null values from ListLINQ 从列表中选择空值
【发布时间】:2015-07-15 08:41:25
【问题描述】:

我有一个List<string>,它可能在随机索引中包含空值。我想检查哪些元素 null 并选择那些元素来抛出消息。

我在用什么;

List<string> getNames = EbaUsers.GetNamesFromIds(activeDirectoryInfo[7],
 activeDirectoryInfo[8], activeDirectoryInfo[9], activeDirectoryInfo[10]);

if(getNames[7].Equals(null))
{
     MessageBox.Show("getNames[7] is null");
}
if(getNames [8].Equals(null))
{
     MessageBox.Show("getNames[8] is null");
}
if(getNames[9].Equals(null))
{
     MessageBox.Show("getNames[9] is null");
}
if(getNames[10].Equals(null))
{
     MessageBox.Show("getNames[10] is null");
}

我知道使用 LINQ 很容易做到这一点,但我没有找到任何地方。

感谢您的帮助。

【问题讨论】:

    标签: linq select null where


    【解决方案1】:

    听起来您想首先将字符串投影到索引/值对,然后选择具有空值的元素,然后仅投影到索引:

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

    【讨论】:

      【解决方案2】:

      您需要通过Enumerable.Select() with index获取索引并检查该信息是否为空:

      var nullInfoIndexes = activeDirectoryInfo.Select((info, index) => new {info, index})
                                               .Where(x => x.info == null)
                                               .Select(x => x.index);
      foreach (var index in nullInfoIndexes)
          MessageBox.Show("activeDirectoryInfo[" + index + "] is null");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多