首页 > 编程语言 >C#比较两个 List 内容是否相同

C#比较两个 List 内容是否相同

时间:2022-11-17 17:13:32浏览次数:53  
标签:return 相同 C# List item False sourceCollection 字典

开发过程中,遇到要比较两个List值是否相同的场景,比如考试答题跟答案是否相同来判断是否答对。

一、简单比较两个int类型的List是否相同,如下:

List<int> rightAnswerList = new List<int>() {1,2};//标准答案
List<int> examAnswerList = new List<int>() {1,3};//考试答题答案
bool isRight = examAnswerList.All(p => rightAnswerList.Any(r => r.Equals(p))) && examAnswerList.Count == rightAnswerList.Count;

二、开发过程中也许还好遇到比较两个其它类型的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 (KeyValuePair<TKey, TValue> 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;
    }

后面这个方法是另一个博主写的,参考一下,原文链接:https://blog.csdn.net/u014661152/article/details/107098263

标签:return,相同,C#,List,item,False,sourceCollection,字典
From: https://www.cnblogs.com/qingheshiguang/p/16899873.html

相关文章

  • .NET Core 项目Linux环境下生成二维码
    问题:公司系统开发中,需要对企微授权链接进行二维码生成,然后向客户提供;当然,首当其冲想到的是使用ZXing.NET库进行实现,毕竟生成简单二维码也就那几句代码;然而,在本地环境中,一......
  • Contos7进入紧急模式 Failed to mount /home
    服务器重启后进入了紧急模式,附图所示:依提示journalctl-xb查看系统日志,发现是/home目录挂载异常:解决:使用管理口或KVM设备登录服务器。1.取消开机自动挂载。注释掉“/......
  • C++中的无穷大
    参考如果问题中各数据的范围明确,那么无穷大的设定不是问题,在不明确的情况下,很多程序员都取0x7fffffff作为无穷大,因为这是32-bitint的最大值。如果这个无穷大只用于一般的......
  • .NET Core 获取程序运行环境信息与反射的应用
    笔者的九篇反射系统文章已经完结,但是笔者会持续更新反射在日常撸码中的应用。本篇内容主要是.NETCore获取运行环境信息、利用反射更加方便地处理数据。本篇内容有:Runti......
  • VS code如何设置中文or其他语言
     打开VScode界面,键盘按快捷键Ctrl+Shift+P,界面上就会出现一个命令行输入框,输入ConfigureDisplayLanguage(配置显示语言)。Tips:点击时不要点最右那个小设置符号 ......
  • JavaScript语法-特殊语法、流程控制语句
    JavaScript语法-特殊语法<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>特殊语法</title><script>//1、语句以;结尾.......
  • Reversing Linked List
    Givenaconstant K andasinglylinkedlist L,youaresupposedtoreversethelinksofevery K elementson L.Forexample,given L being1→2→3→4→5......
  • .net core 获取本地ip及request请求端口
    1.获取ip和端口stringstr=(Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString()+":"+Request.HttpContext.Connection.LocalPort); 输出s......
  • NSSCTF-SWPUCTF2021新生赛之fakerandom
    Day1NSSCTF[SWPUCTF2021新生赛]fakerandom下载源件之后是一个py文件,打开后源码如下随后看到了一个随机数种子,关于随机数种子的知识我了解的不多,只在学校的石头剪刀......
  • Rundeck部署和基本使用【转】
    rundeck介绍Rundeck是一款能在数据中心或云环境中的日常业务中使程序自己主动化的开源软件。Rundeck 提供了大量功能。能够减轻耗时繁重的体力劳动。团队能够相互协作......