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

Linq分组合并

时间:2015-06-17 00:46:29      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

有一个List,要求按日期分组,将同一天的数据组合起来,用Linq实现。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>()
            {
                new Student(){ ID = 1 , Name ="guwei1", BirthDay=DateTime.Now.AddHours(-11), Phone="123456781"},
                new Student(){ ID = 2 , Name ="guwei2", BirthDay=DateTime.Now.AddHours(2).AddDays(2), Phone="123456782"},
                new Student(){ ID = 3 , Name ="guwei3", BirthDay=DateTime.Now.AddHours(-13), Phone="123456783"},
                new Student(){ ID = 4 , Name ="guwei4", BirthDay=DateTime.Now.AddHours(4).AddDays(4), Phone="123456784"},
            };

            var result = from p in students
                         group p by p.BirthDay.ToString("yyyy-MM-dd") into g
                         let q = students.Where(x => x.BirthDay.ToString("yyyy-MM-dd") == g.Key)
                         select new
                         {
                             ID = q.Select(y => y.ID),
                             Name = q.Select(y => y.Name),
                             BirthDay = g.Key,
                             Phone = q.Select(y => y.Phone),
                         };

            foreach (var item in result)
            {
                Console.WriteLine("ID:{0} Name:{1} BirthDay:{2} Phone:{3}",
                    string.Join(",", item.ID),
                    string.Join(",", item.Name),
                    item.BirthDay,
                    string.Join(",", item.Phone));
            }
        }
    }

    public class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public DateTime BirthDay { get; set; }

        public string Phone { get; set; }
    }
}


技术分享

可以看到,按照日期进行了分组,并将其它属性的数据项进行了合并显示。

Linq分组合并

标签:

原文地址:http://blog.csdn.net/chinacsharper/article/details/46525031

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