Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat of two list using LINQ

Tags:

linq

I have two list list1 and list2

List1 contains

1   a
2   b
3   c
4   d

List2 contains

3   c
4   d
5   e

I want following list using LINQ

1   a
2   b
3   c
4   d
5   e
like image 684
Manoj Pilania Avatar asked Mar 20 '13 12:03

Manoj Pilania


3 Answers

List1.Concat(List2.Where(l2 => !List1.Contains(l2))).ToList()
like image 140
Oliver Avatar answered Oct 08 '22 06:10

Oliver


Since I don't see this answer here i'll post it...

The best way to remove duplicates while merging two lists together is Enumerable.Union:

var foo = new List<char> { 'a', 'b', 'c', 'd' };
var bar = new List<char> { 'c', 'd', 'e' };

var result = foo.Union(bar).ToList();

The rest of the answers work, but Linq has a built-in way to do this.

like image 38
Danny North Avatar answered Oct 08 '22 07:10

Danny North


var Lst = List1.Concat(List2.Where(l2 => List1.All(x => x.Id != l2.Id))).ToList();
like image 32
Nitesh Kumar Avatar answered Oct 08 '22 07:10

Nitesh Kumar