我有一个数据集(汽车):
Brand DateSold Amount
Toyota 06/07/2015 18.5
BMW 01/01/2016 25.15
Mercedes 06/06/2016 20.75
我想按年份分组并返回金额的总和,即:
Year Amount
2015 18.5
2016 45.9
并将其输出到列表框中。我尝试过:
var AmountsByYear = cars
.GroupBy(x => new { x.Date.Year })
.Select(x => String.Format("{0}", new {Date =
x.Key.Year, Amount = x.Sum(z => z.Amount)})).ToList();
lstAmountsByYear.Items.Add(AmountsByYear);
和:
var AmountsByYear = cars
.GroupBy(i => i.Date.Year)
.Select(g => new
{Year = g.Key,
Total = g.Sum(i => i.Amount)}).ToList();
lstAmountsByYear.Items.Add(AmountsByYear);
答案 0 :(得分:1)
您的错误在这一行:
lstAmountsByYear.Items.Add(AmountsByYear);
Add
需要一个项目,而不是一个列表。您在此处添加列表,然后显示其类型名称。
如果此集合具有AddRange
方法,则可以执行以下操作:
lstAmountsByYear.Items.AddRange(AmountsByYear);
否则,您需要分别添加每个项目:
foreach(var item in AmountsByYear)
lstAmountsByYear.Items.Add(item);