准备资料如下:
代码语言:javascript复制namespace ListDemo
{
class Book:IComparable<Book>
{
public int Id { get; set; }
public string? Name { get; set; }
public double Price { get; set; }
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 == Name && other.Price == this.Price) return true;
return false;
}
public int CompareTo(Book? other)
{
if (other == null) return 1;
return this.Id - other.Id;
}
}
}
代码语言:javascript复制using ListDemo;
List<double> lst1 = new List<double> { 80.0, 70.0, 60.0, 50.0, 40.0, 30.0, 20.0, 10.0 };
Book book1 = new Book { Id = 1, Name = "Book-1", Price = 10 };
Book book2 = new Book { Id = 2, Name = "Book-2", Price = 20 };
Book book3 = new Book { Id = 3, Name = "Book-3", Price = 30 };
Book book4 = new Book { Id = 4, Name = "Book-4", Price = 40 };
Book book5 = new Book { Id = 5, Name = "Book-5", Price = 50 };
Book book6 = new Book { Id = 6, Name = "Book-6", Price = 60 };
Book book7 = new Book { Id = 1, Name = "Book-1", Price = 10 };
List<Book> lst2 = new List<Book> { book1, book2, book3, book4,book5, book6 };
var res = lst2.Find(e => e.Price % 3 == 0);
Console.WriteLine(res);
res = lst2.FindLast(e => e.Price % 3 == 0);
Console.WriteLine(res);
var res1=lst2.FindAll(e => e.Price % 3 == 0);
Console .ForegroundColor = ConsoleColor.Green;
Console.WriteLine(String .Join(";", res1));
Console.ForegroundColor = ConsoleColor.White ;
Console.WriteLine(lst1.FindIndex(e => e % 3 == 0));
Console.WriteLine(lst2.FindIndex(e => e.Price % 3 == 0));
Console.WriteLine(lst2.FindIndex(3,e => e.Price % 3 == 0));
Console.ForegroundColor = ConsoleColor.Red;
lst1.Sort();
Console.WriteLine(lst1 .BinarySearch (30));
lst2.Sort();
var res3 = lst2.BinarySearch(book7);
Console.WriteLine(res3);
Console.ReadLine();