C# List<T>的Contains、Exists、Any、Where性能对比

1、Contains方法

Contains方法的作用是检查List中是否包含指定元素,其代码实现如下

List<string> list = new List<string>() { "a", "b", "c", "d" };

bool isExists = list.Contains("a");

Contains方法的执行时间非常短,一般在1毫秒以下。因为该方法使用了二分查找算法,在大多数情况下,找到指定元素只需要遍历集合的一半即可,所以执行速度非常快。

2、Exists方法

Exists方法是一个实例方法,可以使用委托作为它的参数来查找元素,其代码实现如下:

List<string> list = new List<string>() { "a", "b", "c", "d" };

bool isExists = list.Exists(x => x == "a");

由于Exists方法的参数是一个委托,所以其执行时间比Contains方法要长。但是,当集合中元素比较多且查找条件复杂时,Exists方法的执行时间可能比Contains方法更短。

3、Any方法

Any方法用于判断集合中是否存在满足指定条件的元素,其代码实现如下:

List<string> list = new List<string>() { "a", "b", "c", "d" };

bool isExists = list.Any(x => x == "a");

Any方法的执行时间与Exists方法相当,因为它们两个的代码实现方式都是一样的。

4、Where方法

Where方法用于筛选符合指定条件的元素,其代码实现如下:

List<string> list = new List<string>() { "a", "b", "c", "d" };

var result = list.Where(x => x == "a");

Where方法的返回值是一个IEnumerable,因为它只是筛选符合指定条件的元素,而并没有直接返回元素本身。由于Where方法是延迟求值的,所以需要使用foreach等方式来获取其返回值。

由于Where方法返回的是延迟求值的IEnumerable,其执行时间比其他方法要长一些。但是,如果需要对集合进行复杂的筛选操作时,Where方法是一个非常好用的API。

相关推荐
农村小镇哥1 小时前
C#中的字符串格式化
服务器·开发语言·c#
这是柠檬君1 小时前
Microsoft Activation Scripts(MAS)最新版!
windows·office
xinhuanjieyi2 小时前
cargo在windows系统下编译成exe,用everything搜索路径
windows·everything
IT曙光4 小时前
OpenClaw 安装与初始化指南windows
windows·openclaw
tinygone4 小时前
在Windows上部署Unlimited-ocr并提供给大模型使用
人工智能·windows·经验分享
WangWei_CM4 小时前
[原创][Windows C++]Winlogon 登录相关注册表值与 Notify 子键解析
windows
czhc11400756635 小时前
719:StartPoint;Margin;ResourceDictionar;Component.model;lds;
c#
一路向北North5 小时前
windows如何部署deepseek
windows
之歆5 小时前
从 Mac 回到 Windows:用 PowerToys + AutoHotkey 找回熟悉手感
windows·macos
geovindu7 小时前
java: Divide and Conquer Algorithm
java·开发语言·windows·后端·算法·分治算法