如何使用 Union 在 LINQ 的匿名类型中分配可为 null 的 int 属性?

How to assign a nullable int property in an anonymous type in LINQ with a Union?

我在 LINQ 中有两个 select 语句和一个 Union.

A RoleID 需要在其中一个 select 中有一个空值。我收到以下错误。

如果 RoleID 有一个值,它工作正常。 Reports 是一个具有属性的 EF 实体。

在这个例子中可以是任何东西。出于说明目的,示例很简单。

LinqPad 中的代码:

var list = Reports.Select(r => new
    {
        RoleID = 3
    })
    .Union(Reports.Select(r => new
    {
        RoleID = new Nullable<int>()    <= error
        //RoleID = (int?) null          <= error
        //RoleID = 4                    <= works
    }));
list.Dump();

如何让它使用空值并使 RoleID 成为 int 类型?

错误信息:

'System.Linq.IQueryable' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union(System.Linq.ParallelQuery, System.Collections.Generic.IEnumerable)' has some invalid arguments Instance argument: cannot convert from 'System.Linq.IQueryable' to 'System.Linq.ParallelQuery'

您还需要 RoleID 在第一个匿名 class 中可以为空:

Reports.Select(r => new
               {
                   RoleID = (int?)3
               }

另请参阅这些问题:

  • 如果两个匿名 class 使用相同的属性、相同的类型、相同的顺序,它们将共享相同的类型:is order of field important in anonymous types automatic initialization?
  • 您还可以创建一个匿名类型的列表并添加到其中:Add an anonymous class of object to an anonymous list
  • 此外,您通常希望使用 Concat,而不是 UnionUnion Vs Concat in Linq

您的第一个 Select 查询 returns 匿名对象序列,其中 RoleID 的类型为 int。要合并两个序列,它们应该具有相同类型的匿名对象。所以你需要改变第一个查询:

var list = Reports.Select(r => new
                {
                    RoleID = (int?)3
                })

请记住,在第二个查询中,您还应该具有可为空的 RoleID 以匹配匿名对象的类型:

 .Union(Reports.Select(r => new
    {
        RoleID = new Nullable<int>() 
        //RoleID = (int?)null
        //RoleID = (int?)4
    }));

顺便说一句,为什么对来自同一来源的两个选择进行联合?看起来您过度简化了示例查询。