首页 新闻 会员 周边 捐助

LINQ 如何实现两次分组?GroupBy() GroupBy()

0
[已解决问题] 解决于 2016-05-10 17:07

一张表里的数据想根据日期分组,然后再根据班级分组,

list.GroupBy(g=>g.Date)    .GroupBy(g=>g.Class)

这样是错的,请教怎么写?

Eysa的主页 Eysa | 初学一级 | 园豆:62
提问于:2016-04-13 19:19
< >
分享
最佳答案
0
public class DemoEntity
    {
        public int Date { get; set; }

        public string Class { get; set; }

        public override string ToString()
        {
            return String.Format("{0}-{1}", Date, Class);
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            List<DemoEntity> myList = new List<DemoEntity>();
            myList.Add(new DemoEntity() { Date = 1, Class = "C1" });
            myList.Add(new DemoEntity() { Date = 1, Class = "C2" });
            myList.Add(new DemoEntity() { Date = 1, Class = "C1" });
            myList.Add(new DemoEntity() { Date = 2, Class = "C1" });
            myList.Add(new DemoEntity() { Date = 2, Class = "C2" });
            myList.Add(new DemoEntity() { Date = 2, Class = "C3" });
            myList.Add(new DemoEntity() { Date = 2, Class = "C2" });

            var result = myList.GroupBy(g => new { g.Class, g.Date });
            result.ToList().ForEach(i => i.ToList().ForEach(a => Console.WriteLine(a.ToString())));
            Console.ReadKey();
        }

奖励园豆:5
Firen | 大侠五级 |园豆:5385 | 2016-04-13 20:09
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册