基本上,我有两个 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/