Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ:一个列表中的值等于另一个列表中的值_C#_Linq - Fatal编程技术网

C# LINQ:一个列表中的值等于另一个列表中的值

C# LINQ:一个列表中的值等于另一个列表中的值,c#,linq,C#,Linq,我有两个对象列表,我想比较特定的属性。如果每个列表中的记录具有相同的指定属性值,我希望查询返回true 我目前正在使用嵌套的foreach循环来完成这项工作,不过我希望使用单个LINQ来完成这项工作 bool doesEachListContainSameFullName = false; foreach (FullName name in NameList) { foreach (FullName anotherName in AnotherNameList) {

我有两个对象列表,我想比较特定的属性。如果每个列表中的记录具有相同的指定属性值,我希望查询返回true

我目前正在使用嵌套的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;
}

我应该补充一点,每个列表中都有一些字段彼此不相等,因此直接比较这两个字段不是一个选项。

您可以使用
任何
方法执行相同的操作

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 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();
    }
}
class FullNameEqualityComparer:IEqualityComparer
{
公共布尔等于(全名x,全名y)
{
返回(x.First==y.First&&x.Last==y.Last);
}
public int GetHashCode(全名obj)
{
返回obj.First.GetHashCode()^obj.Last.GetHashCode();
}
}

我在每个列表中寻找一条记录,以使我指定的所有属性的值相等。我不是在寻找完全相同的列表,也不是在寻找完全相同的记录。如果这不清楚或者我误解了你的问题,我很抱歉。我也很抱歉,我没有理解你的意图。因此,您只需要知道这两个列表是否包含至少一条匹配记录(通过指定的属性进行比较)?正确。在这种情况下,如果列表a中的记录和列表B中的记录具有相同的FirstName和LastName,则无论其他属性是否匹配,我都希望返回true。确定后,我编辑我的答案。这与@Asad的答案很接近,但比较处理得更好。