1

我有一堂课:

public Class MyClass
{
  public string name {get;set;}
  public double quantity {get; set;}
  public double price {get; set;}
  public double value {get; set;}
  public string id1 {get; set;}
  public string id2 {get; set;}
}


List<MyClass> myList = new List<MyClass>();

然后填充列表对象,但相同的名称可以有多个条目。例如,这是我的列表概述:

[0] "stock A", 200.0, 20.0, 4000, "aa", "bb"
[1] "stock A", 400.0, 20.0, 8000, "aa", "bb"
[2] "stock B", 200.0, 20.0, 4000, "cc", "dd"
[3] "stock A", 200.0, 19, 3800, "aa", "bb"
[4] "stock C", 200.0, 20.0, 4000, "ee", "ff"

目前我有以下代码:

var groupedStockList = (from t in myList
  group t by new { t.name, t.price }
    into grp
    select new
    {
      grp.Key.name,
      grp.Key.price,

      Quantity = grp.Sum(x => x.quantity)
    }).ToList();

结果是股票 A 被分组,但 2 组价格为 2 组,所以我有一组价格为 20 的 600 只股票 A 和价格为 19 的 200 只股票。

我在想我必须以平均价格去,即,sum = (quantity * price) / total_quantity但我迷失了如何将其纳入 linq。

有没有人有办法可以帮忙?我想将 ids 1 和 2 也保留在列表中,并按名称排序。

谢谢。

编辑

我想回报的是这个,

[0] "stock A", 800, 19.75, 15800, "aa", "bb"
[1] "stock B", 200.0, 20.0, 4000, "cc", "dd"
[2] "stock C", 200.0, 20.0, 4000, "ee", "ff"
4

2 回答 2

5

尝试这个

var groupedStockList = (from t in myList
    group t by new { t.name, t.id1, t.id2 } into grp
    select new
    {
      Name = grp.Key.name,
      TotalQuantity = grp.Sum(x => x.quantity),
      AvgPrice = grp.Sum(x => x.value) / grp.Sum(x => x.quantity),
      TotalValue = grp.Sum(x => x.value),
      Id1 = grp.Key.id1,
      Id2 = grp.Key.id2     
    }).ToList();
于 2013-10-02T16:23:03.090 回答
0

值得一提的是,使用方法语法而不是查询语法来修改其他答案

var result = myList.GroupBy(x => {x.name, x.id1, x.id2})
                   .Select(g => new {
                                         Name = grp.Key.name,
                                         TotalQuantity = grp.Sum(x => x.quantity),
                                         AvgPrice = grp.Average(x => x.price),
                                         TotalValue = grp.Sum(x => x.value),
                                         Id1 = grp.Key.id1,
                                         Id2 = grp.Key.id2     
                                     })
                   .ToList();
于 2013-10-02T16:31:48.073 回答