日期:2014-05-17  浏览次数:20814 次

请问List<T>如何分组?
List<Student> student = new List<Student>();

以上是我自定义的一个泛型学生类,包含“姓名”、“年龄”、“班级”、“学号”等属性,现在要按照某一个属性对其进行分组,

例如:student 中有10条记录,现在要按照班级分类,其中第1、2条是同一班级、第3、4条是同一班级、第5、6、7条是同一班级、第8、9、10条是同一班级,我需要把它分成4组,并得到分组以后的List,然后循环它,去执行后面的操作,请问这个分组的方法应该怎么写?

------解决方案--------------------
C# code
List<Student> testStr = new List<Student>();
            //添加testStr 元素
            IEnumerable<IGrouping<string, Student>> query = testStr.GroupBy(x => x.班级);
            foreach (IGrouping<string, Student> info in query)
            {
                List<Student> sl = info.ToList<Student>();//分组后的集合
                foreach (Student item in sl)
                {
                    
                }
            }

------解决方案--------------------
2.0就用Dictionary
我写了个小DEMO,你看一下

C# code

class Program
    {
        static void Main(string[] args)
        {
            List<Student> list = new List<Student>()
           {
           new Student{Name="aaa",ClassName="a",Age=20,StuNo="a001"},
           new Student{Name="bbb",ClassName="a",Age=18,StuNo="a003"},
           new Student{Name="ccc",ClassName="b",Age=20,StuNo="b001"},
           new Student{Name="ddd",ClassName="b",Age=20,StuNo="b045"},
           new Student{Name="eee",ClassName="c",Age=20,StuNo="c001"},
           new Student{Name="fff",ClassName="c",Age=20,StuNo="c008"},
           new Student{Name="ggg",ClassName="c",Age=20,StuNo="c050"},
           new Student{Name="hhh",ClassName="c",Age=20,StuNo="c007"}
           };
            Dictionary<string, List<Student>> stuGroup = new Dictionary<string, List<Student>>();
            
            foreach (Student item in list)
            {
                if (!stuGroup.Keys.Contains(item.ClassName))
                {
                    stuGroup.Add(item.ClassName, new List<Student>());
                }
                stuGroup[item.ClassName].Add(item);

            }
            foreach (KeyValuePair<string,List<Student>> item in stuGroup)
            {
                Console.WriteLine("班级:"+item.Key);
                foreach (Student stu in item.Value)
                {
                    Console.WriteLine("姓名:" + stu.Name + "\t班级:" + stu.ClassName + "\t年龄:" + stu.Age + "\t学号:" + stu.StuNo);
                }
            }
            Console.Read();
        }
    }
    class Student
    {
        public string Name { get; set; }

        public string ClassName { get; set; }

        public int Age { get; set; }

        public string StuNo { get; set; }

    }