Paul
Paul

Reputation: 12819

Adding only new items from one list to another

I have two lists:

List<string> _list1;
List<string> _list2;

I need add all _list2 different items on _list1...

How can I do that using LINQ?

Thanks

Upvotes: 4

Views: 7117

Answers (3)

Lee
Lee

Reputation: 144206

// Add all items from list2 except those already in list1
list1.AddRange(list2.Except(list1));

Upvotes: 10

Justin Niessner
Justin Niessner

Reputation: 245479

You would use the IEnumerable<T>.Union method:

var _list1 = new List<string>(new[] { "one", "two", "three", "four" });
var _list2 = new List<string>(new[] { "three", "four", "five" });

_list1 = _list1.Union(_list2);

// _distinctItems now contains one, two, three, four, five

EDIT

You could also use the method the other post uses:

_list1.AddRange(_list2.Where(i => !_list1.Contains(i));

Both of these methods are going to have added overhead.

The first method uses a new List to store the Union results (and then assigns those back to _list1).

The second method is going to create an in-memory representation of Where and then add those to the original List.

Pick your poison. Union makes the code a bit clearer in my opinion (and thus worth the added overhead, at least until you can prove that it is becoming an issue).

Upvotes: 10

Carlos Mu&#241;oz
Carlos Mu&#241;oz

Reputation: 17824

_list1.AddRange( _list2.Where(x => !_list1.Contains(x) ) );

Upvotes: 5

Related Questions