LINQ Union Error - 无法推断类型

时间:2012-05-31 10:11:34

标签: linq types union

我只想尝试在2个linq查询上执行简单的联合,如下所示:

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);

但是我收到以下错误:

  

方法'System.Linq.Enumerable.Union的类型参数(System.Collections.Generic.IEnumerable,   System.Collections.Generic.IEnumerable)'无法推断   从用法。尝试明确指定类型参数。

有谁能指导我如何解决这个问题?

提前致谢

CM

2 个答案:

答案 0 :(得分:2)

您正在尝试合并两种不同的(匿名)类型,这是不可能的。您可以创建自己的类型来存储Key值,以便两个查询都投射到相同的类型。

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
                     };

答案 1 :(得分:1)

为使编译器成功推断出union的结果类型,Query1和Query2返回的两个匿名类型必须相同(实际上,编译器生成单个类型)。

重命名匿名类型的属性,以便两者都使用ab,不会混合。 a.Keyb.Key也需要属于同一类型。

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);