c# – 比较两个(Integer)列表是否相等

栏目: C# · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/13075218/comparing-two-listsof-integer-for-equality
我知道这个非常类似的问题已经被问过很多次,例如在 Comparing two collections for equality irrespective of the order of items in them

,但是我正在尝试使用我正在那里阅读的解决方案而且有些东西不起作用……这是一个愚蠢的错误我’制作…请帮助!!

好的,所以,这是我的场景,假设我在代码中创建了以下3个列表:

Dim lst1 as new list(of integer)
Dim lst2 as new list(of integer)
Dim lst3 as new list(of integer)

然后,在代码中,我最终得到了列表中的以下值:

lst1:    lst2:    lst3:
1        1        2
2        2        3
3        3        4
4        4        5

显然,lst1& lst2是相等的,lst1& lst3不是,但是我可以在if语句中写入哪些代码来验证这一点?

我试过了:

lst1.SequenceEqual(lstXX)

并且对于lst2和lst3都返回True

我试过了:

lst1.Equals(lstXX)

并且对于lst2和lst3都返回False

现在,我知道我可以使用代码比较count和lst1.Except(lstXX),但我想知道更多,所以我在这里做错了,更重要的是,最有效的方法是什么?

谢谢!!!

假设您希望 排序 很重要, SequenceEqual 正是您想要的 – 在您给出的样本中,lst1.SequenceEqual(lst3)将返回false.这是一个简短但完整的程序来演示:
using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main(string[] args)
    {
        var lst1 = new List<int> { 1, 2, 3, 4 };
        var lst2 = new List<int> { 1, 2, 3, 4 };
        var lst3 = new List<int> { 2, 3, 4, 5 };

        Console.WriteLine(lst1.SequenceEqual(lst2)); // True
        Console.WriteLine(lst1.SequenceEqual(lst3)); // False
    }
}

翻译自:https://stackoverflow.com/questions/13075218/comparing-two-listsof-integer-for-equality


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Programming Interface

The Linux Programming Interface

Michael Kerrisk / No Starch Press / 2010-11-6 / GBP 79.99

The Linux Programming Interface describes the Linux API (application programming interface)-the system calls, library functions, and other low-level interfaces that are used, directly or indirectly, b......一起来看看 《The Linux Programming Interface》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具