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 <= 0 || b.Count <= 0 || 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;
    }

}

结果:

猜你喜欢

转载自www.cnblogs.com/zhyue93/p/list.html