How to get Unique objects from two lists in c#?

I have two list objects like

list1   =[{"id":"101","name":"one"},{"id":"102","name":"two"},{"id":"103","name":"three"}]
list2   =[{"id":"111","name":"one"},{"id":"112","name":"two"},{"id":"114","name":"four"},{"id":"115","name":"five"}]

In the above two lists contains duplicate name values . now i want to get the unique name objects based on name attribute. OutPut:-

result   =[{"id":"103","name":"three"},{"id":"114","name":"four"},{"id":"115","name":"five"}]

Upvotes: 1

Views: 4409

Answers (3)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Suppose you have list of model after JSON deserialization process:

var list1 = new List<Model>();
var list2 = new List<Model>();

Since you need to remove all elements that intersect in each list and returns unique elements, use either Except or RemoveAll:

var target = list1.Except(list2);

// or use:
var target = list1.RemoveAll(item => list2.Contains(item));

Another way using HashSet:

var hashSet = new HashSet<Model>(list2);
list1.RemoveAll(item => hashSet.Contains(item));

Reference: Remove elements from one List<T> that are found in another

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16966

You could using Linq extension functions and do this.

var result = list1.Concat(list2)
     .GroupBy(x=>x.name)
     .Where(x=>x.Count() == 1)
     .Select(x=>x.FirstOrDefault())
     .ToList();     

Upvotes: 2

Sami
Sami

Reputation: 3800

var common = list1.Select(a => a.name).Intersect(list2.Select(b => b.name));

Upvotes: 0

Related Questions