Linq分組合并,linq分組

來源:互聯網
上載者:User

Linq分組合并,linq分組

有一個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; }    }}


可以看到,按照日期進行了分組,並將其它屬性的資料項目進行了合并顯示。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.