我是靠谱客的博主 无情电源,这篇文章主要介绍详解C# List<T>的Contains,Exists,Any,Where性能对比,现在分享给大家,希望可以做个参考。

测试

新建一个Person类

复制代码
1
2
3
4
5
6
7
8
9
10
11
public class Person { public Person(string name,int id) { Name = name; Id = id; } public string Name { get; set; } public int Id { get; set; } }

初始化List 中有一百万条数据,然后分别通过每种方法判断xiaoming是否在List中,代码如下

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
static void Main(string[] args) { List<Person> persons = new List<Person>(); //初始化persons数据 for (int i = 0; i < 1000000; i++) { Person person = new Person("My" + i,i); persons.Add(person); } Person xiaoming=new Person("My999999", 999999); //下面通过三种方法判断persons中是否包含xiaoming Stopwatch watch = new Stopwatch(); watch.Start(); bool a = persons.Contains(xiaoming); watch.Stop(); Stopwatch watch1 = new Stopwatch(); watch1.Start(); bool b = persons.Exists(x=>x.Id==xiaoming.Id); watch1.Stop(); Stopwatch watch2 = new Stopwatch(); watch2.Start(); bool c = persons.Where(x=>x.Id==xiaoming.Id).Any(); watch2.Stop(); Stopwatch watch3 = new Stopwatch(); watch3.Start(); bool d = persons.Any(x => x.Id == xiaoming.Id); watch3.Stop(); Console.WriteLine("Contains耗时:" + watch.Elapsed.TotalMilliseconds); Console.WriteLine("Exists耗时:" + watch1.Elapsed.TotalMilliseconds); Console.WriteLine("Where耗时:" + watch2.Elapsed.TotalMilliseconds); Console.WriteLine("Any耗时:" + watch3.Elapsed.TotalMilliseconds); Console.ReadLine(); }

执行结果如下图所示

结论

通过上图可以看出性能排序为

Contains > Exists > Where > Any

注意:
Contains中不能带查询条件

到此这篇关于详解C# List<T>的Contains,Exists,Any,Where性能对比的文章就介绍到这了,更多相关C# Contains,Exists,Any,Where内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是无情电源最近收集整理的关于详解C# List<T>的Contains,Exists,Any,Where性能对比的全部内容,更多相关详解C#内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(129)

评论列表共有 0 条评论

立即
投稿
返回
顶部