Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two list<object> in C# and retain only the items that don't have duplicates?

Tags:

c#

Here are two lists:

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"}, 
        };

now what I want to happen is to get a list that doesn't have duplicates, basically compare list1 and list2 return only the items that are duplicate.

based from the sample what it should return are the last two items from list 2 since they are not in list1.

like image 639
Randel Ramirez Avatar asked May 18 '15 08:05

Randel Ramirez


2 Answers

Try this

list2.Except(list1).Concat(list1.Except(list2));
like image 112
yohannist Avatar answered Sep 29 '22 20:09

yohannist


Basically, the task can be solved with Linq by using

var Result = list1.Concat(list2).Except(list1.Intersect(list2));

however this probably requires UserGroupMap to implement the interface IEquatable<UserGroupMap> in a suitable way, unless UserGroupMap is a struct. If implementation of IEquatable<UserGroupMap> for some reason is impossible, the overload of Except which takes a custom comparison as an argument can be used, as well as the overload of Intersect which takes a custom comparison as an argument.

like image 39
Codor Avatar answered Sep 29 '22 21:09

Codor