I have two select statements in LINQ with a Union
.
A RoleID
needs to have a null value in one of the selects. I am getting the error below.
If the RoleID
has a value, it works fine. Reports is an EF entity with properties.
It can be anything in this example. Example is simple for illustration purposes.
Code in 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();
How do I make it work with a null value and make RoleID of type int?
Error Message:
'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'
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ in C#. Anonymous types contain one or more public read-only properties.
In some cases, you might want to project a query to a new type, but the query would be your only use for the new type. Rather than create the type, you can project to an anonymous type.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
Your first Select
query returns sequence of anonymous objects where RoleID
have type int
. To union both sequences they should have same type of anonymous objects. So you need to change first query:
var list = Reports.Select(r => new
{
RoleID = (int?)3
})
Keep in mind, in second query you also should have nullable RoleID
to match type of anonymous object:
.Union(Reports.Select(r => new
{
RoleID = new Nullable<int>()
//RoleID = (int?)null
//RoleID = (int?)4
}));
BTW Why have union on two selects from same source? Looks like you over simplified your sample queries.
You need RoleID
to be nullable in the first anonymous class as well:
Reports.Select(r => new
{
RoleID = (int?)3
}
See also these questions:
Concat
, not Union
: Union Vs Concat in Linq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With