当前位置: 代码迷 >> C# >> linq怎么groupby时间的日期
  详细解决方案

linq怎么groupby时间的日期

热度:79   发布时间:2016-05-05 03:24:44.0
linq如何groupby时间的日期
table一列是时间,现在我要按日期groupby,把同一天的数据组合起来,由于还有时分秒在里面,这个该怎么处理

------解决思路----------------------
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; }
    }
}

------解决思路----------------------
DataTable dt = new DataTable();
            var query = from r in dt.AsEnumerable()
                        group r by r.Field<DateTime>("date").Date into g
                        select g;

DataTable的
  相关解决方案