c#/ linq数据分组

时间:2012-02-03 10:49:52

标签: c# linq group-by

我有一个Product类,如:

class Product
{
  public string Name;
  public int Year;
  public int Vendor;
  public int Count;
}

数据输入,如

Name Year Vendor Count

'A'  1990   1     15

'A'  1990   2     20

'A'  1998   4     5

'B'  1995   1     15

'B'  1995   2     2

我想将数据转换为像

这样的新结构
class NewStructure
{
 public string Name;
 public int Year;
 Dictionary<int, int> Vendor_Count;
} 

字典字段用于存储{Vendor,Count}对,Name和Year对将具有对应字典。结果将是

Name Year Vendor Count

'A'  1990   1  15

            2  20

'A'  1998   4  5

'B'  1995   1  15

            2   2

我尝试了以下linq查询

from input in inputList
group inputList by new { input.Name, input.Year }
into grouping
orderby grouping.Key.Name, grouping.Key.Year
select new
{
   ProductName = grouping.Key.Name,
   OriginYear = grouping.Key.Year,
   Vendor_Count = grouping.
 } 

但我无法让'Vendor_Count'正确。我不知道该怎么办?

2 个答案:

答案 0 :(得分:2)

如果(名称,年份,供应商)的组合是唯一的,请使用此选项:

inputList.GroupBy(x => new { x.Name, x.Year })
         .Select(x => new
                      {
                          ProductName = x.Key.Name,
                          OriginYear = x.Key.Year, 
                          Vendor_Count = x.ToDictionary(y => y.Vendor
                                                        y => y.Count)
                      })
         .OrderBy(x => x.ProductName).ThenBy(x => x.OriginYear);

如果它不是唯一的,请使用它:

inputList.GroupBy(x => new { x.Name, x.Year })
         .Select(x => new
                      {
                          ProductName = x.Key.Name,
                          OriginYear = x.Key.Year, 
                          Vendor_Count = x.GroupBy(y => y.Vendor)
                                          .ToDictionary(y => y.Key,
                                                        y => y.Sum(z => z.Count))
                      })
         .OrderBy(x => x.ProductName).ThenBy(x => x.OriginYear);

答案 1 :(得分:1)

这样的事情:

        var p1 = new Product(){Count=15, Name="A", Vendor = 1, Year = 1990};
        var p2 = new Product() { Count = 20, Name = "A", Vendor = 2, Year = 1990 };
        var p3 = new Product() { Count = 5, Name = "A", Vendor = 4, Year = 1998 };
        var p4 = new Product() { Count = 15, Name = "B", Vendor = 1, Year = 1995 };
        var p5 = new Product() { Count = 2, Name = "B", Vendor = 1, Year = 1995 };

        var inputList = new[] {p1, p2, p3, p4, p5};

        var newStructure = inputList
            .GroupBy( p => new { p.Name, p.Year } )
            .Select( g => new { g.Key.Name, g.Key.Year, VendorCount = g.ToDictionary(p => p.Vendor, p => p.Count) }
          );

虽然我认为您不能将供应商用作字典键,因为它们并不是唯一的