相关疑难解决方法(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万
查看次数

检查两个列表是否有碰撞元素?

有没有办法检查一个列表是否与另一个列表发生冲突?例如:

    bool hit=false;
    foreach(var s in list2)
    {
        if (list1.Contains(s))
        {
            hit = true;
            break;
        }
    }
    if (!hit)
    {
Run Code Online (Sandbox Code Playgroud)

.net c# collections list

23
推荐指数
1
解决办法
5646
查看次数

标签 统计

.net ×2

collections ×2

c# ×1

comparison ×1

equality ×1

list ×1