码迷,mamicode.com
首页 > 其他好文 > 详细

LINQ技巧:如何通过多次调用GroupBy实现分组嵌套

时间:2016-05-25 22:08:54      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

问题如上,解决如下,目标在最下面:

using System;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
public class Sdata
{
public string gather;
public int shotcount;

}

static void Main(string[] args)
{
var m = new[]{
new Sdata{gather = "100002",shotcount = 28},
new Sdata{gather = "100002", shotcount =44},
new Sdata{gather = "100003", shotcount = 8},
new Sdata{gather = "100003", shotcount = 20},
new Sdata{gather = "100004", shotcount = 55},
new Sdata{gather = "100004", shotcount = 60},
new Sdata{gather = "100005", shotcount = 10},
new Sdata{gather = "100005", shotcount = 60},
new Sdata{gather = "100006", shotcount = 24},
new Sdata{gather = "100006", shotcount = 75},
new Sdata{gather = "100010", shotcount = 41},
new Sdata{gather = "100010", shotcount = 81},
new Sdata{gather = "100012", shotcount = 75},
new Sdata{gather = "100012", shotcount = 100},
};

var q2 =
from s in m
group s by s.gather into gatherGroup
select new
{
gather = gatherGroup.Key,
shotcountGroups =
from s2 in gatherGroup
group s2 by s2.shotcount into shotcountGroups
select new
{
shotcount = shotcountGroups.Key,
//Days =
// from s3 in shotcountGroups
// orderby s3.Day
// select s3.Day
}
};

foreach(var item in q2)
{
Console.WriteLine("1gather={0}",item.gather);
foreach(var itme2 in item.shotcountGroups)
{
Console.WriteLine("\tshotcount = {0}",itme2.shotcount);
}
}

var q = m.GroupBy(
s => s.gather,
(gather, gatherGroup) => new
{
gather,
shotcountGroups =
gatherGroup.GroupBy(
s2 => s2.shotcount,
(shotcount, shotcountGroups) => new
{
shotcount,
//Days = shotcountGroups.OrderBy(s3 => s3.Day).Select(s3 => s3.Day)
}
)
}
);

foreach (var elem in q)
//foreach (var elem in q2)
{
Console.WriteLine("2gather = {0}", elem.gather);
foreach (var elem2 in elem.shotcountGroups)
{
Console.WriteLine("\tshotcount = {0}", elem2.shotcount);
//foreach (var day in elem2.Days)
// Console.WriteLine("\t\tDay = {0}", day);
}

}

Console.Read();
}
}
}

结果: 

gather = 100002
  shotcount = 28
  shotcount = 44
gather = 100003
  shotcount = 8
  shotcount = 20
gather = 100004
  shotcount = 55
  shotcount = 60
gather = 100005
  shotcount = 10
  shotcount = 60
gather = 100006
  shotcount = 24
  shotcount = 75
gather = 100010
  shotcount = 41
  shotcount = 81
gather = 100012
  shotcount = 75
  shotcount = 100

LINQ技巧:如何通过多次调用GroupBy实现分组嵌套

标签:

原文地址:http://www.cnblogs.com/qiri07/p/5528506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!