C# 2个List比较内部项是否相等(全部相等则相等,反之不相等)

时间:2023-03-09 00:26:09
C# 2个List<T>比较内部项是否相等(全部相等则相等,反之不相等)
static void Main(string[] args)
{
List<string> a = new List<string>() { "a", "a", "v", "c", "c" };
List<string> b = new List<string>() { "v", "c", "a", "a", "c" };
List<string> c = new List<string>() { "v", "c", "a", "a", "a" }; Console.WriteLine(a.Equal_EveryItem(b));
Console.WriteLine(a.Equal_EveryItem(c));
Console.WriteLine(b.Equal_EveryItem(c));
Console.ReadKey();
}

调用的方法(作为List的扩展方法)

public static class ListTool
{
/// <summary>
/// 判断List<T> a里面的项是否每一个都和List<T> b一致(顺序可以不一样)
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool Equal_EveryItem<T>(this List<T> a, List<T> b)
{
if (a == null || b == null || a.Count <= || b.Count <= || a.Count != b.Count) return false;
bool result = true;
foreach (var a_item in a)
{
if (b.Exists(b_item => b_item.Equals(a_item)))
{
b.Remove(a_item);
}
else
{//不存在
result = false;
break;
}
} return result;
} }

结果:

C# 2个List<T>比较内部项是否相等(全部相等则相等,反之不相等)