User
User

Reputation: 1662

Compare list in C#

I create two lists like,

            var list = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("1", "abc"));
            list.Add(new KeyValuePair<string, string>("2", "def"));
            list.Add(new KeyValuePair<string, string>("3", "ghi"));


            var list2 = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("1", "abc"));
            list.Add(new KeyValuePair<string, string>("2", "def"));
            list.Add(new KeyValuePair<string, string>("3", "ghi"));
            list.Add(new KeyValuePair<string, string>("4", "jkl"));

           var unmatchedlist= new List<KeyValuePair<string, string>>();

how to compare the two lists.now I need list.Add(new KeyValuePair("4", "jkl")); (because it is not in firstlist but its avail in secondlist )in unmatchedlist?

Upvotes: 0

Views: 164

Answers (3)

4b0
4b0

Reputation: 22323

one way to do this :

list1 = list1.Union(list2);

OR :

list1.AddRange(list1.Except(list2));

Upvotes: 2

Nick N.
Nick N.

Reputation: 13559

Check this way

//This will be empty
var difference1 = list1.Except(list2);

Or the other way arround

//This will contain item 4
var difference2 = list2.Except(list1);

Upvotes: 0

Ric
Ric

Reputation: 13248

This will get you the differences between list2 and list:

var unmatched = list2.Except(list);

Then just add the items into list that appear in unmatched.

Upvotes: 0

Related Questions