I want to combine two LINQ query results into one:
var query1 = from sn in code
group sn by sn.Substring(0, 10) into g
select new
{
Key = g.Key,
Cnt = g.Count(),
Min = g.Min(v => v.Substring(10, 4)),
Max = g.Max(v => v.Substring(10, 4))
};
var query2 = from sn1 in codes
group sn1 by sn1.Substring(0, 11) into g
select new
{
key = g.Key,
Cnt = g.Count(),
Min = g.Min(v => v.Substring(11, 4)),
max = g.Max(v => v.Substring(11, 4))
};
var query3= query1.Union(query2)
but on compilation I get an error:
‘
System.Collections.Generic.IEnumerable<AnonymousType#1>‘ does not
contain a definition for ‘Union‘ and the best extension method
overload
‘System.Linq.Queryable.Union<TSource>(System.Linq.IQueryable<TSource>,‘ has some invalid
System.Collections.Generic.IEnumerable<TSource>)
arguments
what’s wrong with my code?
In the first query you select to an anonymous type with the properties “Key, Cnt, Min, Max”, in the second you use the properties “key, Cnt, Min, max”. This will result in two different anonymous types, because “Key” is not equal to “key” and “max” is not equal to “Max”. And you can’t use union with two different types.
Change your second query to this: