c# - .NET 检查两个 IEnumerable<T> 是否具有相同的元素

标签 c# .net linq list set

<分区>

Possible Duplicate:
Comparing two collections for equality

我需要验证两个 IEnumerable<T>列表具有相同的元素,不一定以相同的顺序。

我的目标是 .NET 3.5。

这是测试。问题是,应该如何HasSameElements()实现?

var l1 = new[]{1,2,3};
var l2 = new[]{3,1,2};

bool rez1 = l1.HasSameElements(l2);//should be true

var l3 = new[]{1,2,3,2};
var l4 = new[]{3,1,2,2};
bool rez2 = l3.HasSameElements(l4);//should be true

var l5 = new[]{1,2,3,2};
var l6 = new[]{1,2,3};
bool rez3 = l5.HasSameElements(l6);//should be false

附加说明:

  • 在示例中,我使用的是 IEnumerable,但 T 可以是任何东西。 T 是否必须实现 IComparable

  • Enumerable.SequenceEquals() 本身不起作用,它希望元素具有相同的顺序。

  • 这是 HasElements 的模板:

[只是一些占位符文本作为 Markdown“代码格式”错误的解决方法]

public static class Extensions {
    public static bool HasElements(this IEnumerable<T> l1, IEnumerable<T> l2){
        throw new NotImplementedException();
    } 
}

最佳答案

只需构建一个字典,将每个对象映射到它在序列中出现的次数,然后检查生成的字典是否相等。

这里:

static class EnumerableExtensions {
    public static bool HasSameElementsAs<T>(
        this IEnumerable<T> first,
        IEnumerable<T> second
    ) {
        var firstMap = first
            .GroupBy(x => x)
            .ToDictionary(x => x.Key, x => x.Count());
        var secondMap = second
            .GroupBy(x => x)
            .ToDictionary(x => x.Key, x => x.Count());
        return 
            firstMap.Keys.All(x =>
                secondMap.Keys.Contains(x) && firstMap[x] == secondMap[x]
            ) &&
            secondMap.Keys.All(x =>
                firstMap.Keys.Contains(x) && secondMap[x] == firstMap[x]
            );
    }
}

显然,重复的代码可以重构为辅助方法,但这只会混淆这里的想法。您可能会喜欢并接受用于 GroupBy 操作的 IEqualityComparer。此外,您应该通过添加 null 守卫等等来生产代码。

关于c# - .NET 检查两个 IEnumerable<T> 是否具有相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4042101/

相关文章:

c# - 类访问问题

c# - 在 SortedDictionary 中查找最接近的值

.net - 您使用什么解决方案在部署后自动测试 Web 应用程序的运行状况或有效性? (。网)

.net - 对于使用服务堆栈创建的服务,如何使用 SSL 保护我的服务?

c# - XML Linq 新手问题

c# - 将单个对象插入 json 文件而不重写整个文件

c# - 为什么我的 Asp.Net Core 日志中出现 "POST requests are not supported"?

c# - 如何绘制 DataGridViewComboBox 列中的非事件行?

C# linq 求和

c# - 在 BindingList<T> 中找不到 Select() 方法,包括 System.Linq