如何为以下输出编写Linq查询

时间:2016-08-23 10:05:37

标签: c# linq

var Shopping= new[] 
{
    new { Code = 1, Name = "Store 1", Type="Test1", Value="Bean"},
    new { Code = 1, Name = "Store 1", Type="Test2", Value="Broccoli"},
    new { Code = 2, Name = "Store 1", Type="Test1", Value="Beetroot"},
    new { Code = 11, Name = "Store 2", Type="Test1", Value="Apple"},
    new { Code = 11, Name = "Store 2" , Type="Test2", Value="Mango"}    
};

输出:

存储1

  Code Test1 Test2
   1   Bean  Broccoli
   2         Beetroot

存储2

  Code Test1 Test2
   11  Apple Mango

如何在Linq C#中查询以下输出?

1 个答案:

答案 0 :(得分:0)

要获得你想要达到的目标,你需要做2 GroupBy s。首先是Name(商店),然后是Code分组。最终,为了从不同的行中获取您想要的不同字段,它被称为旋转。

var result = Shopping.GroupBy(item => item.Name)
        .Select(group => new
        {
            Store = group.Key,
            Items = group.GroupBy(item => item.Code)
                         .Select(innerGroup => new
                         {
                             Code = innerGroup.Key,
                             //This is the pivoting part - I create a "column" and collect under it all the values for that type
                             Test1 = innerGroup.Where(item => item.Type == "Test1").Select(item => item.Value).ToList(),
                             Test2 = innerGroup.Where(item => item.Type == "Test2").Select(item => item.Value).ToList(),
                         }).ToList()
        }).ToList();
  1. 注意:您的数据中存在错误 - Value的记录 Beetroot应该Type Test2而不是Test1 为了得到你想要的。
  2. 我添加了所有ToLists()只是为了方便调试 - 不需要它们。
  3. 您也可以将其转换为字典:

    var stores = Shopping.GroupBy(item => item.Name)
            .Select(group => new
            {
                Store = group.Key,
                Items = group.GroupBy(item => item.Code)
                             .Select(innerGroup => new
                             {
                                 Code = innerGroup.Key,
                                 Test1 = innerGroup.Where(item => item.Type == "Test1").Select(item => item.Value).ToList(),
                                 Test2 = innerGroup.Where(item => item.Type == "Test2").Select(item => item.Value).ToList(),
                             }).ToDictionary(key => key.Code, value => value)
            }).ToDictionary(key => key.Store, value => value.Items);
    

    然后可以通过写result["Store 1"][1].Test1

    来访问它