【发布时间】: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<AccountAlert>() -
这很奇怪:
xAccountStuff.Where(x => x.prop == "prop").ToList() ?? Enumerable.Empty<AccountAlert>()-- 如果 xAccountStuff 为空,它会抛出调用 Where 的异常。如果它不为 null,则 ToList() 将始终返回一个列表。你的意思是(xAccountStuff ?? Enumerable.Empty<AccountAlert>()).Where(...)?或者在 C#6 中,xAccountStuff.?Where(x => x.prop == "prop").ToList() ?? Enumerable.Empty<AccountAlert>()——注意 ``xAccountStuff.?` 之后的问号。 -
ToList将永远返回 null。如果没有匹配Where子句,它将返回一个空的“集合”。 -
仅供参考,那些是编译器错误,而不是例外。异常发生在运行时。