【问题标题】:Remove from a list where a elements value is null从元素值为空的列表中删除
【发布时间】:2014-02-26 17:19:55
【问题描述】:

我正在尝试从列表中的列表中删除有空值的列表。

例如:

responses.Questions[0].Options[0].Value = "asdf";
responses.Questions[0].Options[1].Value = null;
responses.Questions[0].Options[2].Value = 1;

我想删除列表中的第二个选项,因为该值为空。所以当我完成后,我有一个这样的列表:

responses.Questions[0].Options[0].Value = "asdf";
responses.Questions[0].Options[1].Value = 1;

我尝试了下面的代码,但它似乎不起作用:

responses.Questions.Select(q => q.Options.RemoveAll(o => o.Value == null));

【问题讨论】:

    标签: c# asp.net-mvc linq list lambda


    【解决方案1】:

    使用foreach:

    foreach(var q in responses.Questions)
    {
        q.Options.RemoveAll(o => o.Value == null);
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      responses.Questions.ForEach(q => q.Options.RemoveAll(o => o.Value == null));
      

      【讨论】:

      • 太棒了,我选择这个是因为它是一体式的。
      • 我仍然想知道为什么Select 变体不起作用。虽然这是对 Select 的误用,但它应该仍然有效。
      【解决方案3】:

      使用Where 子句以排除null 选项列表:

      responses.Questions
          .Where(q => q.Options != null)
          .ForEach(q => q.Options.RemoveAll(o => o.Value == null));
      

      (根据您现在删除的其中一个 cmets,您遇到了一个异常,因为 Optionsnull。)

      注意:null 值可以出现在此处的不同级别。 responsesQuestionsqOptions 理论上都可以是 null。在适当的地方添加测试。

      【讨论】:

      • 谢谢我在点击添加评论后很快就明白了。我确实这样做了
      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 2019-04-06
      • 2016-05-28
      • 1970-01-01
      • 2018-11-30
      • 2013-11-25
      相关资源
      最近更新 更多