class Collection { /// /// 数据结构:数组 /// List list = new List(); public static void Test() { Collection c = new Collection(); c.listTest(); Console.ReadKey(); } private void InitList() { Student st1 = new Student("张三", 17, 1000); Student st2 = new Student("李四", 20, 1001); Student st3 = new Student("王五", 18, 1000); Student st4 = new Student("赵六", 19, 1001); Student st5 = new Student("钱七", 18, 1003); Student st6 = new Student("张九", 21, 1002); list.Add(st1); list.Add(st2); list.Add(st3); list.Add(st4); list.Add(st5); list.Add(st6); } public void listTest() { this.InitList(); foreach (var item in list) { Console.WriteLine(item); } Console.WriteLine("\n*****根据Id分组*****"); var query = list.GroupBy(pet => pet.Id); // IEnumerable> query = list.GroupBy((st) => { return st.Id; }); // IEnumerable> query = list.GroupBy(ListGroud); foreach (var item in query) { List stt = item.ToList(); Console.WriteLine("key::" + item.Key); foreach (var item2 in stt) { Console.WriteLine(item2); } Console.WriteLine(""); } Console.WriteLine("\n获取元素在列表中的下标:" + list.BinarySearch(list[2])); Console.WriteLine("\n列表根据对象属性A,转换成属性A为key的字典对象(要保证建唯一):"); var dictionary2 = list.ToDictionary(st => st.Name); foreach (var item in dictionary2) { Console.WriteLine("key:" + item.Key + " ->value:" + item.Value); } Console.WriteLine("\n根据条件筛选:"); var tempList = list.Where(a => a.Name.Contains("张") || a.Name.Contains("李")).ToList(); // List tempList = list.FindAll(st => st.Name.Contains("张") || st.Name.Contains("李")); foreach (var item in tempList) { Console.WriteLine(item); } Console.WriteLine("\n计算列表中年龄总和:" + list.Sum(st => st.Age)); ; list.Take(3); //获取列表前3项 list.Skip(4); //截取(跳过前4条数据) var kk = list.GetRange(1, 3); //从第1项起,获取后面三项,可以做分页。 bool b = list.Exists(st => st.Name == "张三"); //判断是否存在某个属性 var templist = list.OrderBy(st => st.Id); //根据某个属性排序 list.Sort(); //排序要求对象实现IComparable接口 foreach (var item in templist) { Console.WriteLine(item); } int maxAge= list.Max(st => st.Age); Student ss= list.Max(); } private int ListGroud(Student st) { return st.Id; } } public class Student:IComparable { public int Age; public int Id; public string Name; public Student(string name, int age, int Id) { this.Name = name; this.Age = age; this.Id = Id; } public override string ToString() { return string.Format("编号:{0}、姓名:{1}、年龄:{2}", this.Id, this.Name, this.Age); } public int CompareTo(object obj) { return this.Id > ((Student)obj).Id ? 1 : -1; } }