C# 为什么Null是无效的LINQ投影?

C# 为什么Null是无效的LINQ投影?,c#,linq,C#,Linq,我有以下语句,它总是返回null: var addins = allocations.SelectMany( set => set.locations.Any(q => q.IsMatch(level, count)) ? (List<string>)set.addins : null ); var addins=allocations.SelectMany( set=>set.locations.Any(q=>q.IsMatc

我有以下语句,它总是返回null:

var addins = allocations.SelectMany(
        set => set.locations.Any(q => q.IsMatch(level, count))
        ? (List<string>)set.addins : null
     );
var addins=allocations.SelectMany(
set=>set.locations.Any(q=>q.IsMatch(级别,计数))
?(列表)set.addins:null
);
我稍微修改了一下,现在可以正常工作了:

var addins = allocations.SelectMany(
        set => set.locations.Any(q => q.IsMatch(level, count))
        ? set.addins : new List<string>()
     );
var addins=allocations.SelectMany(
set=>set.locations.Any(q=>q.IsMatch(级别,计数))
?set.addins:新列表()
);
我的主要问题是:在LINQ的上下文中,为什么null不能作为三元运算符的返回类型

第二个问题:有没有更聪明的方法来表述上述查询(特别是如果它消除了“new List()”)


(List)set.addins:(List)null
可枚举。SelectMany将尝试枚举lambda返回的序列,并在尝试调用null上的GetEnumerator()时引发NullReferenceException。您需要提供一个实际的空序列。不必创建新列表,您可以使用:

var addins=allocations.SelectMany(
set=>set.locations.Any(q=>q.IsMatch(级别,计数))
?(列表)set.addins:Enumerable.Empty()
);
我想你真正想要的是在SelectMany之前调用Where来筛选出你不想要的集合:

var addins = allocations
    .Where(set => set.locations.Any(q => q.IsMatch(level, count)))
    .SelectMany(set => (List<string>)set.addins);
var addins=分配
.Where(set=>set.locations.Any(q=>q.IsMatch(level,count)))
.SelectMany(set=>(List)set.addins);
或者,在查询语法中:

var addins =
    from set in allocations
    where set.locations.Any(q => q.IsMatch(level, count))
    from addin in (List<string>)set.addins
    select addin;
var附加值=
从集合中分配
其中set.locations.Any(q=>q.IsMatch(level,count))
从(列表)集合中的加载项。加载项
选择addin;

出色的回答和见解。顺便说一句,在您的其他示例中不需要对“set.addins”进行强制转换,因为不涉及三元运算符。
var addins =
    from set in allocations
    where set.locations.Any(q => q.IsMatch(level, count))
    from addin in (List<string>)set.addins
    select addin;