class Simple
{
string Company;
int Count;
decimal Amount;
};
var balance = bal.GroupBy(d => d.Compnay).Select(
cl => new
{
Company = cl.Key,
Count = cl.Count(),
Amount = cl.Sum(c => c.Amount)
});
List<Simple> summary = new List<Simple>();
summary = balance.ToList();
此处最后一行显示错误&#34;无法隐式转换&#34;
aboe LINQ查询返回匿名类型,如何获取List&lt;&gt;它的对象,即。调用ToList()方法。
答案 0 :(得分:1)
你可以尝试这个:
var balance = bal.GroupBy(d => d.Compnay)
.Select(cl => new
{
Company = cl.Key,
Count = cl.Count(),
Amount = cl.Sum(c => c.Amount)
}).ToList();
<强>更新强>
另一方面,如果您想获得要声明的自定义类型列表,则必须遵循以下内容:
class CustomType
{
public string Company { get; set; }
public int Count { get; set; }
public decimal Amount { get; set; }
}
var balance = bal.GroupBy(d => d.Compnay)
.Select(cl => new CustomType
{
Company = cl.Key,
Count = cl.Count(),
Amount = cl.Sum(c => c.Amount)
}).ToList();
注意第二种方法不会创建对象列表,其类型为匿名类型。它是CustomType
类型的对象列表。另一方面,第一种方法创建了一个对象列表,其类型是匿名类型。
答案 1 :(得分:1)
我想你想要这样的东西:
public class CompanyVM
{
public int Company {get;set;}
public int Count {get;set;}
public int Amount {get;set;}
}
var balance = bal.GroupBy(d => d.Compnay).Select(
cl => new CompanyVM
{
Company = cl.Key,
Count = cl.Count(),
Amount = cl.Sum(c => c.Amount)
}).ToList();
对于你的班级,你必须写:
List<Simple> balance = bal.GroupBy(d => d.Compnay).Select(
cl => new Simple
{
Company = cl.Key,
Count = cl.Count(),
Amount = cl.Sum(c => c.Amount)
}).ToList<Simple>();
答案 2 :(得分:1)
您无法将匿名类型列表分配给已知类型的列表。即使它们具有相同的属性,也不是相同的类型。