获取错误:'System.Collections.Generic.IEnumerable <anonymoustype#1>'不包含'ToList'的定义</anonymoustype#1>

时间:2011-12-09 16:03:54

标签: linq c#-3.0

我正在做以下

List<A> lstA = new List<A>();
            Enumerable.Range(1, 10).ToList().ForEach(i => lstA.Add(new A { Prop1 = i, Prop2 = "Prop2" + i.ToString() }));

            List<B> lstB = new List<B>();
            Enumerable.Range(1, 10).ToList().ForEach(i => lstB.Add(new B { Prop1 = i, Prop3 = DateTime.Now }));

            var res = (from a in lstA
                       join b in lstB on a.Prop1 equals b.Prop1
                       select new
                       {
                           Prop1 = a.Prop1
                           ,
                           Prop2 = a.Prop2
                           ,
                           Prop3 = b.Prop3
                       }).ToList<C>();

表示组合结果要存储在List中。

当时收到错误

  

'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments

怎么做?

class A
    {
        public int Prop1 { get; set; }
        public string Prop2 { get; set; }
    }

    class B
    {
        public int Prop1 { get; set; }
        public DateTime Prop3 { get; set; }        
    }

    class C
    {
        public int Prop1 { get; set; }
        public string Prop2 { get; set; }
        public DateTime Prop3 { get; set; }
    }

由于

2 个答案:

答案 0 :(得分:7)

您正在创建一个新匿名类型的序列,并尝试在其上调用ToList<C>。那不行。简单的解决方案是更改查询以创建C

的序列
var res = (from a in lstA
           join b in lstB on a.Prop1 equals b.Prop1
           // Note the "new C" part here, not just "new"
           select new C
           {
               Prop1 = a.Prop1,
               Prop2 = a.Prop2,
               Prop3 = b.Prop3
           }).ToList();

答案 1 :(得分:2)

您无法将匿名类型转换为C

您应该通过撰写C直接创建new C { ... }