1、定义演示数据类型:
public class TestData
{
public int GrpId { get; private set; }
public int Id { get; set; }
public int IdMod5 { get; private set; }
public string Name { get; set; }
public TestData(int id, string name)
{
Random _random = new Random();
this.Id = id;
this.Name = name;
this.GrpId = this.Id % 3;
this.IdMod5 = this.Id % 6;
}
}
假定已初始化了如图的数据:
2、演示分组时组内排序和组外排序方法:
Console.WriteLine("\r\n演示组内按Name降序和组外按Key.RID升序:");
var numberGroups = from n in testdatas
orderby n.Name descending
group n by new { n.IdMod5, RID = n.GrpId } into g
orderby g.Key.RID
select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine("Id:{0} Name:{1} RID:{2} IdMod5:{3}", n.Id, n.Name, n.GrpId, n.IdMod5);
}
}
运行结果见下图:
3、演示先分组,然后每组里面仅取满足条件的行组:
Console.WriteLine("\r\n演示先分组,然后每组里面仅取Id最大的行组:");
var lets = from a in testdatas
group a by a.GrpId into grp
let maxId = grp.Max(a => a.Id)
from row in grp
where row.Id == maxId
select row;
foreach (var g in lets)
{
Console.WriteLine("Id:{0} Name:{1} RID:{2} IdMod5:{3}", g.Id, g.Name, g.GrpId, g.IdMod5);
}
运行结果如下图: