0

Possible Duplicate:
Merge two object lists with linq

I have 2 Lists of type string:

List1 has items - item1, item2, item3

List2 has items - item1, item4, item5

Now I need to compare both lists and add the missing ones from List2 into List1. The modified List1 will be

list 1 : item1, item2, item3, item4, item5
Community
  • 1
  • 1
Sandeep
  • 5,581
  • 10
  • 42
  • 62
  • 8
    var mergedList = list1.Union(list2).ToList(); http://stackoverflow.com/questions/720609/merge-two-object-lists-with-linq –  Aug 03 '12 at 13:46

5 Answers5

3

you can use LiNQ for this:

List<string> newList = List1.Union(List2).ToList();
John Woo
  • 258,903
  • 69
  • 498
  • 492
1

you can try with this code - Except operator

var result = List2.Except(List1);

foreach(string item in result )
{
   List1.Add(item);
}
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
1

I would use linq to do it

var result = List1.Union(List2);

http://msdn.microsoft.com/en-us/library/bb358407.aspx

Return Value Type: System.Collections.Generic.IEnumerable An IEnumerable that contains the elements from both input sequences, excluding duplicates.

DeMeNteD
  • 385
  • 4
  • 11
0

A simply way:

foreach(string item in List2)
{
if(!List1.Contains(item))
   List1.Add(item);
}

of course there are shorter (lenght of code) options

Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
0

You could use LINQ for this.

Look at the Except method and then join the resulting collection to you original collection.

See: http://csharp.net-tutorials.org/category/linq-to-objects/linq-except/

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100