日期:2014-05-17 浏览次数:20814 次
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,你看一下
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; } }