tags:

views:

65

answers:

4

I want to combine items of two string list but do not want repeated items

List<string> l1 = new List<string>() { "A", "B", "C", "D"};
List<string> l2 = new List<string>() { "B", "E", "G", "D"};

Result: A, B, C, D, E, G

How can i achieve this?

+3  A: 

Use the Union and Distinct operators:

var newList = l1.Union(l2).Distinct().ToList();
Will Vousden
A: 

This should work. Not quite as elegant as the above answer.

        List<string> l1 = new List<string>() { "A", "B", "C", "D" };
        List<string> l2 = new List<string>() { "B", "E", "G", "D" };

        l1.Concat(l2);
        IEnumerable<string> noDupes = l1.Distinct();
Jride
+3  A: 

You can use LINQ to produce the union of the two lists:

var combined = l1.Union(l2);
Bojan Resnik
It won't, as it is defined as set union. From MSDN documentation: `This method excludes duplicates from the return set. This is different behavior to the Concat<(Of <(TSource>)>) method, which returns all the elements in the input sequences including duplicates.`
Bojan Resnik
A: 

C# 2.0 version

Dictionary<string,string> dict = new Dictionary<string,string>();
l1.AddRange(l2);
foreach(string s in l1) dict[s] = s;
List<string> result = new List<string>(dict.Values);
Jonas Elfström