当前位置: 首页> 服务器> 正文

c# list.contains 能否自定义比较逻辑

c# list.contains 能否自定义比较逻辑

是的,在C#中,您可以使用List<T>.Exists()方法或List<T>.FindIndex()方法来自定义比较逻辑。这两个方法都接受一个谓词(Predicate)委托,该委托定义了如何比较列表中的元素。

以下是一个示例,说明如何使用Exists()方法自定义比较逻辑:

using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // 自定义比较逻辑:检查列表中是否存在偶数 bool existsEvenNumber = numbers.Exists(x => x % 2 == 0); Console.WriteLine("Exists even number in the list: " + existsEvenNumber); } }

以下是一个使用FindIndex()方法自定义比较逻辑的示例:

using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // 自定义比较逻辑:找到第一个偶数的索引 int indexOfFirstEvenNumber = numbers.FindIndex(x => x % 2 == 0); Console.WriteLine("Index of first even number in the list: " + indexOfFirstEvenNumber); } }

在这两个示例中,我们使用了lambda表达式来定义比较逻辑。您也可以使用普通的匿名方法或命名方法作为谓词。