开发者

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

开发者 https://www.devze.com 2022-12-11 18:39 出处:网络
which is the fastest way to find the union and intersection between two lists? i mean. i have two list say

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

精彩评论

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

关注公众号