【问题标题】:Setting a List to empty if it is null如果列表为空,则将列表设置为空
【发布时间】:2016-04-27 16:47:09
【问题描述】:

我正在尝试合并两个列表,这些列表中的任何一个都可以为空。我知道您不应该使用空列表,因此我尝试在合并它们之前将它们设置为空列表。问题是,当我尝试连接时,我似乎只能检查第二个列表是否为空,见下文!

List<AccountAlert> xAccountEmails = new List<AccountAlert>();
List<AccountAlert> xAccountPhones = new List<AccountAlert>();
///Lots of things happen

//Below throws a compiler error cannot implicity convert IEnumerable to Generic.List
xAccountEmails = xAccountStuff.Where(x => x.prop == "prop").ToList() ?? Enumerable.Empty<AccountAlert>();
// Below throws the same compiler error
xAccountEmails = xAccountEmails ?? Enumerable.Empty<AccountAlert>();
//Below works!
xAccountPhones = xAccountStuff.Where(x => x.prop == "prop").ToList();
xAccountCombined = xAccountEmails.Concat(xAccountPhones ?? Enumerable.Empty<AccountAlert>()).ToList();

如果要连接到一个空列表,我将如何测试和处理它?

【问题讨论】:

  • 你能发布“xAccountEmails”和“xAccountStuff”是如何初始化的吗?
  • 为什么不直接使用new List&lt;AccountAlert&gt;()
  • 这很奇怪:xAccountStuff.Where(x =&gt; x.prop == "prop").ToList() ?? Enumerable.Empty&lt;AccountAlert&gt;() -- 如果 xAccountStuff 为空,它会抛出调用 Where 的异常。如果它不为 null,则 ToList() 将始终返回一个列表。你的意思是(xAccountStuff ?? Enumerable.Empty&lt;AccountAlert&gt;()).Where(...)?或者在 C#6 中,xAccountStuff.?Where(x =&gt; x.prop == "prop").ToList() ?? Enumerable.Empty&lt;AccountAlert&gt;()——注意 ``xAccountStuff.?` 之后的问号。
  • ToList 将永远返回 null。如果没有匹配 Where 子句,它将返回一个空的“集合”。
  • 仅供参考,那些是编译器错误,而不是例外。异常发生在运行时。

标签: c# linq list


【解决方案1】:

ToList 将永远返回 null。您不需要所有这些 null 检查和转换为列表。如果您将变量声明为IEnumerable&lt;AccountAlert&gt;,您可以这样做:

xAccountEmails = xAccountStuff.Where(x => x.prop == "prop");
xAccountPhones = xAccountStuff.Where(x => x.prop == "prop");

xAccountCombined = xAccountEmails.Concat(xAccountPhones);

【讨论】:

  • 调用它 IEnumerable 和拥有一个 AccountAlerts 列表有什么区别?
  • IEnumerable 更通用——它可以是一个列表、一个数组或枚举底层集合的包装器。它使您不必将所有东西都添加到特定的集合类型中。
【解决方案2】:

首先,检查xAccountStuff 中的null,然后如果需要,可以在调用Where 时声明xAccountEmails 和xAccountEmails 列表。

那些列表永远不会是null,可能是空的,但不是null。

xAccountStuff = xAccountStuff ?? new List<AccountAlert>();

var xAccountEmails = xAccountStuff.Where(x => x.prop == "prop1").ToList();
var xAccountPhones = xAccountStuff.Where(x => x.prop == "prop2").ToList();

var xAccountCombined = xAccountEmails.Concat(xAccountPhones).ToList();

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 2019-04-04
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2016-02-07
    • 2020-07-20
    相关资源
    最近更新 更多