Chris
Chris

Reputation: 7621

Concatenating 2 lists into 1 C# question

I have 2 lists that are used to store int values in C#, and I want to merge these list, but I don't want duplicates in there. I.e. if list 1 has 1,2,4 and list 2 has, 2,3,5 I'd want 1,2,3,4,5 (don't matter about order) in my list. I've tried the Concat method, but that creates duplicates.

Upvotes: 1

Views: 211

Answers (4)

Muad'Dib
Muad'Dib

Reputation: 29266

there are many many ways to do this.

myList<int> result = new List<int>( List1 ).AddRange(List2).Distinct();

Upvotes: 0

TJHeuvel
TJHeuvel

Reputation: 12618

There are probably some very clever and fancy ways to do this, but just a simple foreach loop would work. Just loop over list2, if the index doesnt exist in list1 add it.

Upvotes: 0

MrKWatkins
MrKWatkins

Reputation: 2668

The LINQ Union method should help:

var merged = list1.Union(list2).ToList();

Upvotes: 7

Daniel A. White
Daniel A. White

Reputation: 191048

var newList = list1.Union(list2).ToList();

Upvotes: 3

Related Questions