相关疑难解决方法(0)

比较两个集合的相等性,而不管它们中的项目顺序如何

我想比较两个集合(在C#中),但我不确定有效实现它的最佳方法.

我已经阅读了关于Enumerable.SequenceEqual的其他帖子,但这并不是我正在寻找的.

在我的情况下,如果它们都包含相同的项目(无论顺序),则两个集合将是相等的.

例:

collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1 == collection2; // true
Run Code Online (Sandbox Code Playgroud)

我通常做的是遍历一个集合中的每个项目,看看它是否存在于另一个集合中,然后循环遍历另一个集合的每个项目,看它是否存在于第一个集合中.(我首先比较长度).

if (collection1.Count != collection2.Count)
    return false; // the collections are not equal

foreach (Item item in collection1)
{
    if (!collection2.Contains(item))
        return false; // the collections are not equal
}

foreach (Item item in collection2)
{
    if (!collection1.Contains(item))
        return false; // the collections are not equal
}

return true; // the collections are equal
Run Code Online (Sandbox Code Playgroud)

但是,这并不完全正确,并且它可能不是比较两个集合的最有效方法.

我能想到的一个例子是错误的:

collection1 …
Run Code Online (Sandbox Code Playgroud)

.net collections comparison equality

154
推荐指数
9
解决办法
9万
查看次数

在C#中使用LINQ比较两个List <string>

根据,顺序数量比较两个列表的最佳方法是什么.所以下面的所有列表应该是不同的.

var list1 = new List<string> { "1", "2" };
var list2 = new List<string> { "2", "1" };
var list3 = new List<string> { "1", "2", "3" };
Run Code Online (Sandbox Code Playgroud)

c# linq list

3
推荐指数
1
解决办法
590
查看次数

检查两个字符串数组的等价性

有没有更好的方法来检查两个字符串数组是否具有相同的内容?

string[] first = new string[]{"cat","and","mouse"};
string[] second = new string[]{"cat","and","mouse"};

bool contentsEqual = true;

if(first.Length == second.Length){
    foreach (string s in first)
    {
        contentsEqual &= second.Contains(s);
    }
}
else{
    contentsEqual = false;
}


Console.WriteLine(contentsEqual.ToString());//    true
Run Code Online (Sandbox Code Playgroud)

c#

2
推荐指数
1
解决办法
941
查看次数

标签 统计

c# ×2

.net ×1

collections ×1

comparison ×1

equality ×1

linq ×1

list ×1