LINQ:一个列表中的值等于另一个列表中的值
LINQ: Values from one list equal values from another
我有两个对象列表,我想比较特定的属性。如果每个列表中的记录具有相同的指定属性值,我希望查询 return 为真。
我目前正在使用嵌套的 foreach 循环执行此操作,但我想使用单个 LINQ 来执行此操作。
bool doesEachListContainSameFullName = false;
foreach (FullName name in NameList)
{
foreach (FullName anotherName in AnotherNameList)
{
if (name.First == anotherName.First && name.Last == anotherName.Last)
{
doesEachListContainSameFullName = true;
break;
};
}
if (doesEachListContainSameFullName)
break;
}
我应该补充一点,每个列表中的字段彼此不相等,因此不能直接比较两者。
你可以用Any
方法做同样的事情
return NameList.Any(x => otherList.Any(y => x.First == y.First &&
x.Last == y.Last));
[理解要求后编辑了我的答案]
bool doesEachListContainSameFullName =
NameList.Intersect(AnotherNameList, new FullNameEqualityComparer()).Any();
FullNameEqualityComparer
是一个简单的 class,看起来像这样:
class FullNameEqualityComparer : IEqualityComparer<FullName>
{
public bool Equals(FullName x, FullName y)
{
return (x.First == y.First && x.Last == y.Last);
}
public int GetHashCode(FullName obj)
{
return obj.First.GetHashCode() ^ obj.Last.GetHashCode();
}
}
我有两个对象列表,我想比较特定的属性。如果每个列表中的记录具有相同的指定属性值,我希望查询 return 为真。
我目前正在使用嵌套的 foreach 循环执行此操作,但我想使用单个 LINQ 来执行此操作。
bool doesEachListContainSameFullName = false;
foreach (FullName name in NameList)
{
foreach (FullName anotherName in AnotherNameList)
{
if (name.First == anotherName.First && name.Last == anotherName.Last)
{
doesEachListContainSameFullName = true;
break;
};
}
if (doesEachListContainSameFullName)
break;
}
我应该补充一点,每个列表中的字段彼此不相等,因此不能直接比较两者。
你可以用Any
方法做同样的事情
return NameList.Any(x => otherList.Any(y => x.First == y.First &&
x.Last == y.Last));
[理解要求后编辑了我的答案]
bool doesEachListContainSameFullName =
NameList.Intersect(AnotherNameList, new FullNameEqualityComparer()).Any();
FullNameEqualityComparer
是一个简单的 class,看起来像这样:
class FullNameEqualityComparer : IEqualityComparer<FullName>
{
public bool Equals(FullName x, FullName y)
{
return (x.First == y.First && x.Last == y.Last);
}
public int GetHashCode(FullName obj)
{
return obj.First.GetHashCode() ^ obj.Last.GetHashCode();
}
}