项目常用List来进行数据操作管理,有一些方法经常百度,所以这里记录下。
目录
1. List判断元素是否存在,返回bool
2. List查找,返回对象
3. List排序
4. 对象属性打印
5. List 其他方法
personList.Exists(t => t.name == "John")
Person temp = personList.Find(t => t.name == "Jack" && t.age > 30 && t.sex == true);
完整版测试代码:
namespace CSharpApp { class Person : IComparable<Person> { 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<Person> personList; personList = new List<Person>(); //给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()); //换行输出内容 } } }