1、删除所有值为400的元素
list.RemoveAll(e=>e==400);
2、删除所有能被100整除的元素
list.RemoveAll(e=>e%100==0);
3、求和
int sum=0;
int result = list.ForEach(val=>sum+=val);
4、删除所有值为400的元素
bool result = list.Exists(e=>e==400)
5、是否所有的元素都等于400
bool result = list.TrueForAll(e=>e==400)
6、返回能被100整除的元素(从前向后找)
var result = list.Find(e=>e%100==0);
6、返回能被100整除的元素(从后向前找)
var result = list.FindLast(e=>e%100==0);
7、返回能被100整除的List
var result = list.FindAll(e=>e%100==0);
8、返回能被100整除的索引(从前向后找)
int result = list.FindIndex(e=>e%100==0);
9、返回能被100整除的索引(从后向前找)
int result = list.FindLastIndex(e=>e%100==0);
10、二分查找(速度较快,它的原理是先把排序好的list分成2分,搜索中点值,发现值不对,就可以砍掉这个分组,只剩下一半再查找)
list.Sort();//二分查找前先必须先升序排序
int result = list.BinarySearch(e=>e%100==0);
11、对类(引用类型)进行排序(bookList.Sort()),需要类实现IComparable接口
internal class Book : IComparable<Book>
{
public int ID { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int CompareTo([AllowNull] Book other)
{
if (other == null) return 1;
return this.ID - other.ID;//返回正数,this>other;返回0,this=other;返回负数,this<other;
}
public override string ToString()
{
return JsonSerializer.Serialize(this);
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Book other = obj as Book;
if (other.ID == this.ID && other.Name == this.Name && other.Price == this.Price) return true;
return false;
}
}
12、对类(引用类型)进行二分查找(bookList.BinarySearch()),只能查找相应对象。如果只查找属性一致的对象,需重写Equals()方法,如上所示。