开发者

fastest way to find the union and intersection items among two list

which is the fastest way to find the union and intersection between two lists? i mean. i have two list say List<1>

1

2

3

4

Lis<2>

2

3

Finally i need to get output as

List<3>

Not Defin开发者_开发百科ed

2

3

Not Defined

Hope i am clear with my requirement. Please let me know if i am conusing


LINQ already has Union and Intersection. Your example is neither.

var set = new HashSet(list2)
var list3 = List1.Select(x => set.Contains(x) ? x : null).ToList();


Or you could do the following, which just gives you the intersection:

        HashSet<int> list1 = new HashSet<int>() { 1, 2, 3, 4 };
        HashSet<int> list2 = new HashSet<int>() { 2, 3 };
        List<int> list3 = list1.Intersect(list2).ToList();
        for (int i = 0; i < list3.Count; i++)
        {
            Console.WriteLine(list3[i]);
        }
        Console.ReadLine();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜