Linq:GroupBy

来源:互联网 发布:单片机程序设计实例 编辑:程序博客网 时间:2024/06/04 19:59

linq里面封装了很多方法,其中GroupBy方法用的不是很多,稍微尝试了一下,话不多说,直接上示例:

        static void Main(string[] args)        {            List<Student> students = new List<Student>()            {                new Student() { Name="a",Age=20 },                new Student() { Name="b",Age=20 },                new Student() { Name="c",Age=21 },                new Student() { Name="d",Age=22 },                new Student() { Name="e",Age=21 },                new Student() { Name="f",Age=23 },                new Student() { Name="g",Age=20 }            };            List<IGrouping<int, Student>> result = students.GroupBy(temp => temp.Age).ToList();            foreach(IGrouping<int, Student> group in result)            {                //取IGrouping的组键                int age = group.Key;                Console.WriteLine("分组:");                //取IGrouping得组值                List<Student> studentList = group.ToList<Student>();                studentList.ForEach(temp => { Console.WriteLine("\t" + temp.ToString()); });            }            Dictionary<int, Student> temp1 = new Dictionary<int, Student>();            temp1.Add(1, new Student() { Name = "a", Age = 21 });            temp1.Add(2, new Student() { Name = "b", Age = 21 });            temp1.Add(3, new Student() { Name = "c", Age = 22 });            temp1.Add(4, new Student() { Name = "d", Age = 21 });            Console.ReadKey();        }    }    class Student    {        public string Name { get; set; }        public int Age { get; set; }        public override string ToString()        {            return string.Format("Name:{0}   Age:{1}", this.Name, this.Age);        }    }

这里写图片描述

0 0
原创粉丝点击