在List<T>中,Contains, Exists, Any都可以實作判斷元素是否存在。
性能方面:Contains 優于 Exists 優于 Any
測試的代碼:
public static void Contains_Exists_Any_Test(int num)
{
List<int> list = new List<int>();
int N = num;
for (int i = 0; i < N; i++)
{
list.Add(i);
}
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
Console.WriteLine(list.Contains(N));
sw.Stop();
Console.WriteLine("Contains:"+sw.Elapsed.ToString());
sw.Start();
Console.WriteLine(list.Exists(i => i == N));
sw.Stop();
Console.WriteLine("Exists:"+ sw.Elapsed.ToString());
sw.Start();
Console.WriteLine(list.Any(i => i == N));
sw.Stop();
Console.WriteLine("Any:"+ sw.Elapsed.ToString());
}
在開發過程中可以根據實際情況進行選擇,當list中資料量不大時使用Exists代碼更簡潔易懂;資料量大時推薦使用Contains;不推薦使用Any
下面的代碼對比就能看出為啥資料量不大的時候推薦Exists了。
class ITEM_GIDComparer : IEqualityComparer<T>
{
public bool Equals(T orl1, T orl2)
{
if (orl1==null)
{
return orl2 == null;
}
return orl1.ITEM_GID == orl2.ITEM_GID;
}
public int GetHashCode(T orl)
{
if (orl == null)
return 0;
return orl.ITEM_GID.GetHashCode();
}
}
orlclst.Contains(orlc, new ITEM_GIDComparer())
//Exists一行代碼就可以實作上面的功能
orlclst.Exists(x=>x.ITEM_GID==orlc.ITEM_GID)