Adding only new items from one list to another

I have two lists:

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

I need to add all _list2 different elements to _list1 ...

How to do it with LINQ?

thank

+3
source share
3 answers
list1.AddRange(list1.Except(list2));
+9
source

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

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 can also use a method that uses another post:

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

Both of these methods will have additional overhead.

The first method uses the new list to store the results of the join (and then assigns them back _list1).

The second way is to create a Where memory view, and then add them to the original list.

. , (, , , , , ).

+11
_list1.AddRange( _list2.Where(x => !_list1.Contains(x) ) );
+5
source

Source: https://habr.com/ru/post/1759200/


All Articles