c# - LINQ(或其他东西)比较两个列表中的一对值(以任何顺序)?

标签 c# performance linq comparison ienumerable

基本上,我有两个 IEnumerable<FooClass> s 其中每个 FooClass 实例包含 2 个属性:FirstName、LastName。

每个可枚举对象的实例相同。相反,我需要检查每个实例的属性。我不确定执行此操作的最有效方法,但基本上我需要确保两个列表包含相似的数据(不是相同的实例,但属性上的值相同)。我无权访问 FooClass 本身来修改它。


我应该说 FooClass 是一种 Attribute 类,它可以访问 Attribute.Match()方法,所以我不需要单独检查每个属性。


根据评论,我已将问题更新为更具体并略作更改......这就是我目前所拥有的:

public void Foo()
{
        var info = typeof(MyClass);
        var attributes = info.GetCustomAttributes(typeof(FooAttribute), false) as IEnumerable<FooAttribute>;

        var validateAttributeList = new Collection<FooAttribute>
            {
                new FooAttribute(typeof(int), typeof(double));
                new FooAttribute(typeof(int), typeof(single));
            };

        //Make sure that the each item in validateAttributeList is contained in
        //the attributes list (additional items in the attributes list don't matter).
        //I know I can use the Attribute.Match(obj) to compare.
}

最佳答案

Enumerable.SequenceEqual会告诉您这两个序列是否相同。

如果FooClass有一个被覆盖的 Equals比较 FirstName 的方法和 LastName ,那么你应该能够写:

bool equal = List1.SequenceEqual(List2);

如果FooClass没有覆盖 Equals方法,那么你需要创建一个 IEqualityComparer<FooClass> :

class FooComparer: IEqualityComparer<FooClass>
{
    public bool Equals(FooClass f1, FooClass f2)
    {
        return (f1.FirstName == f2.FirstName) && (f1.LastName == f2.LastName);
    }
    public int GetHashCode()
    {
        return FirstName.GetHashCode() ^ LastName.GetHashCode();
    }
}

然后你写:

var comparer = new FooComparer();
bool identical = List1.SequenceEqual(List2, comparer);

关于c# - LINQ(或其他东西)比较两个列表中的一对值(以任何顺序)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693110/

相关文章:

c# - 下拉列表未在 UpdatePanel 中更新

javascript - 将 C# List<string> 转换为 Javascript

vb.net - ArgumentException 调用 Expression.IfThenElse

c# - 如何使用 linq 表达式将一个方法作为另一个方法的参数传递

javascript - 改善 Javascript 加载时间 - 串联与多个 + 缓存

c# - 扩展 LINQ 的选项

c# - 如何创建一个空的 IOrderedEnumerable<DynamicNode> 和 IEnumerable<IGrouping<string, DynamicNode>>

c# - 如何将 JsonResult.Data 输出转换为原始类型?

performance - Go Web 应用程序是否应该在一个模板中包含所有页面?

language-agnostic - 您将如何以最紧凑的方式为大型组合编写此算法?