Linq GroupBy用法
//定义类
List<Mode> list = new List<Mode>();
list.Add(new Mode() { aa = "a", bb = "b", cc = "1" });
list.Add(new Mode() { aa = "a", bb = "b", cc = "2" });
list.Add(new Mode() { aa = "a", bb = "b", cc = "3" });
list.Add(new Mode() { aa = "a", bb = "22", cc = "1" });
list.Add(new Mode() { aa = "a", bb = "22", cc = "2" });
list.Add(new Mode() { aa = "a", bb = "22", cc = "3" });
//使用匿名对象作为groupBy的Key值(注:使用变量直接赋值会导致GroupBy失效)
var lo = list.GroupBy(a => new { a.aa, a.bb });
List<GroupResult> res = new List<GroupResult>();
foreach (var item in lo)
{
//多个字段进行GroupBy之后Key值中需要单独使用
res.Add(new GroupResult() { group = new Group() { aa = item.Key.aa, bb = item.Key.bb }, lstMode = item.ToList() });
}
public class Mode
{
public string aa { get; set; }
public string bb { get; set; }
public string cc { get; set; }
}
public class GroupResult
{
public Group group { get; set; }
public List<Mode> lstMode { get; set; }
}