Hello... 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
Hello... 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
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).