List<T>中对比Contains, Exists, Any之间的优缺点

原文出处:http://blog.csdn.net/chen46311973/article/details/50057505

在List<T>中,Contains, Exists, Any都可以实现判断元素是否存在。

先上结果。性能方面:Contains 优于 Exists 优于 Any

以下为测试代码

[csharp]  view plain  copy
  1. public static void Contains_Exists_Any_Test(int num)  
  2.         {  
  3.             List<int> list = new List<int>();  
  4.   
  5.             int N = num;  
  6.             for (int i = 0; i < N; i++)  
  7.             {  
  8.                 list.Add(i);  
  9.             }  
  10.             System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();  
  11.             sw.Start();  
  12.             Console.WriteLine(list.Contains(N));  
  13.             sw.Stop();  
  14.             Console.WriteLine("Contains:"+sw.Elapsed.ToString());  
  15.   
  16.             sw.Start();  
  17.             Console.WriteLine(list.Exists(i => i == N));  
  18.             sw.Stop();  
  19.             Console.WriteLine("Exists:"+ sw.Elapsed.ToString());  
  20.   
  21.             sw.Start();  
  22.             Console.WriteLine(list.Any(i => i == N));  
  23.             sw.Stop();  
  24.             Console.WriteLine("Any:"+ sw.Elapsed.ToString());  
  25.         }  

在开发过程中可以根据实际情况进行选择,当list中数据量不大时使用Exists代码更简洁易懂;数据量大时推荐使用Contains;不推荐使用Any。

下面的代码对比就能看出为啥数据量不大的时候推荐Exists了。

[csharp]  view plain  copy
  1. class ITEM_GIDComparer : IEqualityComparer<T>  
  2.     {  
  3.         public bool Equals(T orl1, T orl2)  
  4.          {  
  5.              if (orl1==null)  
  6.              {  
  7.                  return orl2 == null;  
  8.              }  
  9.              return orl1.ITEM_GID == orl2.ITEM_GID;  
  10.          }  
  11.   
  12.         public int GetHashCode(T orl)  
  13.          {  
  14.              if (orl == null)  
  15.                  return 0;  
  16.              return orl.ITEM_GID.GetHashCode();  
  17.          }   
  18.     }  
  19.     orlclst.Contains(orlc, new ITEM_GIDComparer())  
  20.     //Exists一行代码就可以实现上面的功能  
  21.     orlclst.Exists(x=>x.ITEM_GID==orlc.ITEM_GID)  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值