【问题标题】:fastest way to find the union and intersection items among two list在两个列表中查找并集和交集项的最快方法
【发布时间】:2009-11-12 04:05:16
【问题描述】:

找到两个列表之间的并集和交集的最快方法是什么? 我的意思是。 我有两个清单说 列表
1
2
3
4

李斯
2
3

最后我需要得到输出
列表
未定义
2
3
未定义

希望我清楚我的要求。 如果我在混淆,请告诉我

【问题讨论】:

  • 你想要联合还是交集?在您的示例中,“未定义”是否意味着您不在乎发生了什么,或者您希望它实际上说“未定义”?一个/两个列表是否已排序?

标签: c#-3.0


【解决方案1】:

LINQ 已经有 Union 和 Intersection。你的例子都不是。

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

【讨论】:

  • 警告:这会在 list3 中返回空值
【解决方案2】:

或者您可以执行以下操作,这只会为您提供交集:

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

【讨论】:

    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2013-10-12
    • 2021-03-18
    • 2020-10-24
    • 2022-06-15
    相关资源
    最近更新 更多