原文出处: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)  


本文转载:CSDN博客