开发者

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开发者_JAVA技巧 list. I've tried the Concat method, but that creates duplicates.


The LINQ Union method should help:

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


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


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.


there are many many ways to do this.

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜