C#中的列表比较 [英] List comparison in C#

查看:84
本文介绍了C#中的列表比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果主列表不包含新添加的第二项列表,我试图将布尔值设为true。

I am trying to make Boolean value as true if the main list does not contain newly added 2nd items list.

static void Main()
       {
           List<int> toUserIds = new List<int>() { 1,3,4,5};
           List<int> fromUserIds = new List<int>() { 6,1,4,3,5};
           bool isMDNUpdated = false;
           foreach (int userID in fromUserIds)
           {
               if (toUserIds.IndexOf(userID) == -1)
               {
                   isMDNUpdated = true;
                   break;
               }
           }

           Console.WriteLine(isMDNUpdated);
           Console.Read();
       }





我尝试过:



我尝试使用以下代码。

如果此代码不正确,请纠正我。



What I have tried:

I have tried with the below code.
Could you please correct me if this code is not in proper way.

static void Main()
       {
           List<int> toUserIds = new List<int>() { 1,3,4,5};
           List<int> fromUserIds = new List<int>() { 6,1,4,3,5};
           bool isMDNUpdated = false;
           foreach (int userID in fromUserIds)
           {
               if (toUserIds.IndexOf(userID) == -1)
               {
                   isMDNUpdated = true;
                   break;
               }
           }

           Console.WriteLine(isMDNUpdated);
           Console.Read();
       }

推荐答案

嗯......你可以在一行中完成:

Well ... you can do it in a single line:
bool hasNew = fromUserIds.Except(toUserIds).Count() != 0;


解决方案1是正确的,但无需实例化可枚举,然后对其进行计数。当使用任何扩展名遇到第一个差异时,您可以提前退出。

Solution 1 is correct but there is no need to instantiate an enumerable and then count it. You can get an early exit when the first difference is encountered by using the Any extension.

bool isUpdated = fromUserIds.Any(i => !toUserIds.Contains(i));


这篇关于C#中的列表比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆