开发者

combine items of two lists

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

List<string> l1 = new List<string>() { "A"开发者_如何学JAVA, "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();


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

var combined = l1.Union(l2);


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();


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜