ListContains, Exists, Any之间的优缺点对比

时间:2023-03-10 05:57:33
List<T>Contains, Exists, Any之间的优缺点对比

在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)