Reputation: 1391
I'm just trying to perform as simple union on 2 linq queries as below:
var results1 = from a in dt.AsEnumerable()
where array1.Contains([COL_1])
select new
{
a = a.Key
};
var results2 = from b in dt.AsEnumerable()
where array2.Contains([COL_2])
select new
{
b = b.Key
};
var concatResults = results1.Union(results2);
But I am getting the following error:
The type arguments for method 'System.Linq.Enumerable.Union(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Can anyone give me a steer on how to resolve this problem?
Thanks in advance
CM
Upvotes: 1
Views: 1631
Reputation: 460068
For the compiler to successfully infer the type of the result of the union, the two anonymous types returned by Query1 and Query2 need to be identical (in fact, the compiler generates a single type).
Rename the anonymous type's properties so that both uses a
or b
, no mixing. a.Key
and b.Key
also need to be of the same type.
var results1 = from a in dt.AsEnumerable()
join arr1 in array1 on a.Field<int>("Col1") equals arr1
select new
{
Key = a.Field<int>("Key")
};
var results2 = from b in dt.AsEnumerable()
join arr1 in array1 on b.Field<int>("Col2") equals arr1
select new
{
Key = b.Field<int>("Key")
};
var unioned = results1.Union(results2);
Upvotes: 1
Reputation: 34349
You are trying to union two different (anonymous) types, which isn't possible. You could create your own type to store your Key value, so that both queries project to the same type.
public class MyType
{
string Key { get; set; }
}
var results1 = from a in dt.AsEnumerable()
where array1.Contains([COL_1])
select new MyType
{
Key = a.Key
};
etc
Upvotes: 3