如何比较C#中的两个列表<object>并仅保留没有重复项的项?

Ran*_*rez 5 c#

这是两个列表:

var list1 = new List<UserGroupMap> 
        { 
            new UserGroupMap { UserId = "1", GroupId = "1", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"}, 
            new UserGroupMap { UserId = "1", GroupId = "2", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"},
            new UserGroupMap { UserId = "1", GroupId = "3", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"},
            new UserGroupMap { UserId = "2", GroupId = "3", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"} 
        };

        var list2 = new List<UserGroupMap> 
        { 
            new UserGroupMap { UserId = "1", GroupId = "1", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"}, 
            new UserGroupMap { UserId = "1", GroupId = "2", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"},
            new UserGroupMap { UserId = "1", GroupId = "3", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"},
            new UserGroupMap { UserId = "2", GroupId = "3", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"},
            new UserGroupMap { UserId = "4", GroupId = "3", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"}, 
            new UserGroupMap { UserId = "3", GroupId = "3", FormGroupFlag = "1", GroupDescription = "desc1", GroupName = "g1"}, 
        };
Run Code Online (Sandbox Code Playgroud)

现在我想要的是获得一个没有重复的列表,基本上比较list1和list2只返回重复的项目.

根据示例,它应返回的是列表2中的最后两项,因为它们不在list1中.

yoh*_*nes 5

试试这个

list2.Except(list1).Concat(list1.Except(list2));
Run Code Online (Sandbox Code Playgroud)

  • 在UserGroupMap不重写`Equals`和`GetHashCode`之前,这不起作用.目前还不清楚这是如何"返回列表2中不在list1中的最后两项." (2认同)

Cod*_*dor 4

基本上,该任务可以通过使用 Linq 来解决

var Result = list1.Concat(list2).Except(list1.Intersect(list2));
Run Code Online (Sandbox Code Playgroud)

然而,这可能需要以合适的方式UserGroupMap实现接口,除非是. 如果由于某种原因无法实现,则可以使用以自定义比较作为参数的重载,以及以自定义比较作为参数的重载IEquatable<UserGroupMap>UserGroupMapstructIEquatable<UserGroupMap>ExceptIntersect