我正在做以下事情
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>();
Run Code Online (Sandbox Code Playgroud)
表示组合结果要存储在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; }
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您正在创建一个新的匿名类型的序列,并尝试调用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();
Run Code Online (Sandbox Code Playgroud)