C# 判断两个集合(List)是否相等

Stella981
• 阅读 852

1.两个list如果有重复元素(如List1: a,b,a  List2: b,b,a) 是无法通过包含关系来判断是否相等的.

有两个办法,其一是两个List排序后再按顺序比较.另一个办法就是计算各元素的重复项再进行比较

第一种方案劣势太明显,时间复杂度过大

第二种以空间换时间,只需要遍历无需排序即可.

/// <summary>
        /// 判断两个集合是否是相等的(所有的元素及数量都相等)
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="sourceCollection">源集合列表</param>
        /// <param name="targetCollection">目标集合列表</param>
        /// <returns>两个集合相等则返回True,否则返回False</returns>
        public static bool EqualList<T>(this IList<T> sourceCollection, IList<T> targetCollection) where T : IEquatable<T>
        {
            //空集合直接返回False,即使是两个都是空集合,也返回False
            if (sourceCollection == null || targetCollection == null)
            {
                return false;
            }

            if (object.ReferenceEquals(sourceCollection, targetCollection))
            {
                return true;
            }

            if (sourceCollection.Count != targetCollection.Count)
            {
                return false;
            }

            var sourceCollectionStaticsDict = sourceCollection.StatisticRepetition();
            var targetCollectionStaticsDict = targetCollection.StatisticRepetition();

            return sourceCollectionStaticsDict.EqualDictionary(targetCollectionStaticsDict);
        }

        /// <summary>
        /// 判断两个字典是否是相等的(所有的字典项对应的值都相等)
        /// </summary>
        /// <typeparam name="TKey">字典项类型</typeparam>
        /// <typeparam name="TValue">字典值类型</typeparam>
        /// <param name="sourceDictionary">源字典</param>
        /// <param name="targetDictionary">目标字典</param>
        /// <returns>两个字典相等则返回True,否则返回False</returns>
        public static bool EqualDictionary<TKey, TValue>(this Dictionary<TKey, TValue> sourceDictionary, Dictionary<TKey, TValue> targetDictionary)
            where TKey : IEquatable<TKey>
            where TValue : IEquatable<TValue>
        {
            //空字典直接返回False,即使是两个都是空字典,也返回False
            if (sourceDictionary == null || targetDictionary == null)
            {
                return false;
            }

            if (object.ReferenceEquals(sourceDictionary, targetDictionary))
            {
                return true;
            }

            if (sourceDictionary.Count != targetDictionary.Count)
            {
                return false;
            }

            //比较两个字典的Key与Value
            foreach (var item in sourceDictionary)
            {
                //如果目标字典不包含源字典任意一项,则不相等
                if (!targetDictionary.ContainsKey(item.Key))
                {
                    return false;
                }

                //如果同一个字典项的值不相等,则不相等
                if (!targetDictionary[item.Key].Equals(item.Value))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 统计集合的重复项,并返回一个字典
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="sourceCollection">统计集合列表</param>
        /// <returns>返回一个集合元素及重复数量的字典</returns>
        private static Dictionary<T, int> StatisticRepetition<T>(this IEnumerable<T> sourceCollection) where T : IEquatable<T>
        {
            var collectionStaticsDict = new Dictionary<T, int>();
            foreach (var item in sourceCollection)
            {
                if (collectionStaticsDict.ContainsKey(item))
                {
                    collectionStaticsDict[item]++;
                }
                else
                {
                    collectionStaticsDict.Add(item, 1);
                }
            }

            return collectionStaticsDict;
        }

2

public class CommonTest  
    {
        /// <summary>
        /// 集合相等比较
        /// </summary>
        [Fact]
        public void ListEqual_Tests()
        {
            var sourceList = new List<string>()
            {
                "a",
                "b",
                "a"
            };

            var targetList = new List<string>()
            {
                "b",
                "b",
                "a"
            };

            var resp = sourceList.EqualList(targetList);
            Assert.False(resp );
        }

        /// <summary>
        /// 集合相等比较
        /// </summary>
        [Fact]
        public void ListEqual2_Tests()
        {
            var sourceList = new List<string>()
            {
                "a",
                "b",
            };

            var targetList = new List<string>()
            {
                "b",
                "a"
            };

            var resp = sourceList.EqualList(targetList);
            Assert.True(resp);
        }
    }
点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
java 数据结构(十二):Collections工具类的使用
Collections工具类1.作用:操作Collection和Map的工具类2.常用方法:reverse(List):反转List中元素的顺序shuffle(List):对List集合元素进行随机排序sort(List):根据元素的自然顺序对指定List集合元素升序排序sort(List,Comparator)
Wesley13 Wesley13
2年前
java中字符串相等判断
字符串的判断有2种:        1、判断地址是否相等 用:        2、判断值是否相等 用:equals方法Object类作为所有类的超类,而Object类的equals方法是直接比较地址的,源码如下:publicbooleanequals(Objectobj){
Wesley13 Wesley13
2年前
javaAPI_集合基础_List
List集合1.list集合以及其特点list集合是有序的,且可重复的。有序是指:存储的是什么那么遍历出来的也就是什么。2.list集合特有的功能(1).添加功能voidadd(intindex,objectelement):在指定位置添加元素(2).获取功能Objectget(intind
Wesley13 Wesley13
2年前
java基础(五)集合
!(https://images2015.cnblogs.com/blog/875181/201609/875181201609211007331061187286566.png)Collection接口是集合类的根接口,Java中没有提供这个接口的直接的实现类。但是却让其被继承产生了两个接口,就是Set和List。Set中不能包含重复的元素。L
Wesley13 Wesley13
2年前
Java判断两个时间段是否有交集
publicstaticSimpleDateFormatformatnewSimpleDateFormat("yyyyMMddHH:mm:ss");privatestaticbooleanisOverlap(Stringstartdate1,Stringenddate1,Stringstartdate2,String
Stella981 Stella981
2年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Stella981 Stella981
2年前
List、Map、Set三个接口存取元素时,各有什么特点
List接口以特定索引来存取元素,可以有重复元素Set接口不可以存放重复元素(使用equals方法区分是否重复)Map接口保存的是键值对(keyvaluepair)映射,映射关系可以是一对一或者多对一(key唯一)Set和Map容器都有基于哈希存储和排序树的两种实现版本。基于哈希存储的版本的实现理论存取时间复杂度是O(1),而基于排序树版本的
Stella981 Stella981
2年前
JavaScript里面三个等号和两个等号的区别
\equality等同,identity恒等。\,两边值类型不同的时候,要先进行类型转换,再比较。\,不做类型转换,类型不同的一定不等。下面分别说明:先说,这个比较简单。下面的规则用来判断两个值是否相等:1、如果类型不同,就\不相等\2、如果两个都是数值,并且是同
Stella981 Stella981
2年前
Lua 排序算法
冒泡排序(BubbleSort,台湾译为:泡沫排序或气泡排序)是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。算法步骤1.有一个长度为n
菜园前端 菜园前端
10个月前
什么是顺序搜索?
原文链接:什么是顺序搜索?顺序搜索是一种比较低效的搜索算法,但是实现起来相对简单。主要步骤如下:1.遍历数组2.找到跟目标值相等的元素,就返回它的下标3.遍历结束后,如果没有搜索到目标值,则返回1基础案例时间复杂度:O(n)空间复杂度:O(1)javasc