使用Linq的嵌套组

时间:2014-03-27 20:51:30

标签: c# linq

这就是我的模型的样子:

public class ServerData
{
    public string ServerName { get; set; }
    public DateTime DataDate { get; set; }
}

这就是我填充数据的方式。看起来像这样

    List<CapacityData> capData = new List<CapacityData>();
    capData.Add(new CapacityData { ServerName = "Server1", DataDate = DateTime.Today });
    capData.Add(new CapacityData { ServerName = "Server1", DataDate = DateTime.Today.AddDays(-1) });
    capData.Add(new CapacityData { ServerName = "Server1", DataDate = DateTime.Today.AddDays(-2) });

    capData.Add(new CapacityData { ServerName = "Server2", DataDate = DateTime.Today });
    capData.Add(new CapacityData { ServerName = "Server2", DataDate = DateTime.Today.AddDays(-1) });
    capData.Add(new CapacityData { ServerName = "Server2", DataDate = DateTime.Today.AddDays(-2) });

我正在尝试将此结果集分组为两组(Servers和DataDate),以便我可以获得如下数据:

Server1
       01/01/2013
                 Data for 01012013
       01/02/2013
                 Data for 01022013
       01/03/2013
                 Data for 01032013

Server2
       01/01/2013
                 Data for 01012013
       01/02/2013
                 Data for 01022013
       01/03/2013
                 Data for 01032013

我能够为ServerName分组此数据数据,但我无法弄清楚如何进一步对其进行分组,以便数据按DataDate组内的ServerName进行分组。

这就是我的LINQ表达式的样子:

var results = capData.GroupBy(d => d.ServerName,
           (serverNamekey, groupedData) => new { ServerName = serverNamekey, DailyData = groupedData.ToList() });

2 个答案:

答案 0 :(得分:1)

在每个severname组的数据中,您还希望对数据进行分组,因此请获取您的组数据,并按数据对其进行分组:

var results = capData.GroupBy(d => d.ServerName,
    (serverNamekey, groupedData) => new
    {
        ServerName = serverNamekey,
        DailyData = groupedData.GroupBy(capacity => capacity.DataDate)
    });

答案 1 :(得分:1)

您可以按复合键分组:

var results = capData.GroupBy(d => new {d.ServerName, d.DataDate},
           (key, g) => new { ServerName = key.ServerName, 
                             DataDate = k.DataDate, 
                             DailyData = g.ToList() });

让UI处理重复的服务器,或者执行另一个GroupBy

var results = capData.GroupBy(d => d.ServerName)
                     .Select(g => new { ServerName = g.Key, 
                                        DataGroup = g.GroupBy(d => d.DataDate)
                                                     .Select(gg => new { DataDate = gg.Key, 
                                                                         DailyData = gg.ToList()
                                                                       }
                                      });