C#中List常用方法:判断存在、查找、排序

您所在的位置:网站首页 string数组中包含某个元素 C#中List常用方法:判断存在、查找、排序

C#中List常用方法:判断存在、查找、排序

2023-08-18 01:44| 来源: 网络整理| 查看: 265

项目常用List来进行数据操作管理,有一些方法经常百度,所以这里记录下。

目录

1. List判断元素是否存在,返回bool

2. List查找,返回对象

3. List排序

4. 对象属性打印

5. List 其他方法

1. List判断元素是否存在,返回bool

personList.Exists(t => t.name == "John")

2. List查找,返回对象

Person temp = personList.Find(t => t.name == "Jack" && t.age > 30 && t.sex == true);

3. List排序 class Person : IComparable     {         public string name;         public int age;         public bool sex;                 //定义比较方法,按照 age 比较         public int CompareTo(Person other)         {             if (this.age < other.age)             {                 return -1;             }             return 1;         }     } personList.Sort(); 4. 对象属性打印 class Person : IComparable { public string name; public int age; public bool sex; //打印对象实例 public override string ToString() { return "name: " + name + ";age: " + age + ";sex: " + sex; } } person.ToString();

 

完整版测试代码:

namespace CSharpApp { class Person : IComparable { public string name; public int age; public bool sex; public Person(string Name, int Age, bool Sex) { this.name = Name; this.age = Age; this.sex = Sex; } //定义比较方法,按照 age 比较 public int CompareTo(Person other) { if (this.age < other.age) { return -1; } return 1; } //打印对象实例的时候使用 public override string ToString() { return "name: " + name + ";age: " + age + ";sex: " + sex; } } class ListTest { static void Main(string[] args) { List personList; personList = new List(); //给List赋值 Person p1 = new Person("Mike", 30, true); Person p2 = new Person("John", 20, false); Person p3 = new Person("Jack", 50, true); personList.Add(p1); personList.Add(p2); personList.Add(p3); //List排序 personList.Sort(); if (personList.Exists(t => t.name == "John")) { //如果List中存在 name == John的元素 } //查找 name 等于 Jack、年龄大于30、性别男的元素 Person temp = personList.Find(t => t.name == "Jack" && t.age > 30 && t.sex == true); //打印找到的对象实例 //temp.ToString(); Console.WriteLine(temp.ToString()); //换行输出内容 } } } 5. List 其他方法 Count - List元素数量 Add(T item) - 向List添加对象 AddRange() - 尾部添加实现了 ICollection 接口的多个元素 BinarySearch() - 排序后的List内使用二分查找 Clear() - 移除所有元素 Contains(T item) - 测试元素是否在List内 CopyTo(T[] array) - 把List拷贝到一维数组内 Exists() - 判断存在 Find() - 查找并返回List内的出现的第一个匹配元素 FindAll() - 查找并返回List内的所有匹配元素 GetEnumerator() - 返回一个用于迭代List的枚举器 GetRange() - 拷贝指定范围的元素到新的List内 IndexOf() - 查找并返回每一个匹配元素的索引 Insert() - 在List内插入一个元素 InsertRange() - 在List内插入一组元素 LastIndexOf() - 查找并返回最后一个匹配元素的索引 Remove() - 移除与指定元素匹配的第一个元素 RemoveAt() - 移除指定索引的元素 RemoveRange() - 移除指定范围的元素 Reverse() - 反转List内元素的顺序 Sort() - 对List内的元素进行排序 ToArray() - 把List内的元素拷贝到一个新的数组内 trimToSize() - 将容量设置为List中元素的实际数目

 

 

 

 

 

 

 

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3