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?
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?
Use the Union
and Distinct
operators:
var newList = l1.Union(l2).Distinct().ToList();
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();
You can use LINQ to produce the union of the two lists:
var combined = l1.Union(l2);
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);