C# 的两个list怎么判断是否存在交集

要判断两个 List<string>dateListLocalDate)是否有交集,可以使用 LINQ(Language Integrated Query)来简化这个过程。以下三种方法来判断两个列表之间是否有交集。

方法 1: 使用 LINQ 的 Any 方法

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> dateList = new List<string> { "2024-01-01", "2024-02-02", "2024-03-03" };
        List<string> localDate = new List<string> { "2024-03-03", "2024-04-04" };

        bool hasIntersection = dateList.Any(date => localDate.Contains(date));

        if (hasIntersection)
        {
            Console.WriteLine("两个列表有交集。");
        }
        else
        {
            Console.WriteLine("两个列表没有交集。");
        }
    }
}

方法 2: 使用 LINQ 的 Intersect 方法

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> dateList = new List<string> { "2024-01-01", "2024-02-02", "2024-03-03" };
        List<string> localDate = new List<string> { "2024-03-03", "2024-04-04" };

        var intersection = dateList.Intersect(localDate).Any();

        if (intersection)
        {
            Console.WriteLine("两个列表有交集。");
        }
        else
        {
            Console.WriteLine("两个列表没有交集。");
        }
    }
}

方法 3: 使用集合操作

如果要频繁地检查交集,可以考虑将其中一个列表转换为集合(HashSet),这样会提高查找效率。

csharp 复制代码
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> dateList = new List<string> { "2024-01-01", "2024-02-02", "2024-03-03" };
        List<string> localDate = new List<string> { "2024-03-03", "2024-04-04" };

        HashSet<string> dateSet = new HashSet<string>(dateList);
        bool hasIntersection = localDate.Any(date => dateSet.Contains(date));

        if (hasIntersection)
        {
            Console.WriteLine("两个列表有交集。");
        }
        else
        {
            Console.WriteLine("两个列表没有交集。");
        }
    }
}

总结

  • 方法 1方法 2 使用 LINQ 提供了简洁的语法,适合大多数情况。
  • 方法 3 使用集合操作可以在大量数据情况下提高性能,特别是当 localDate 列表较大时。
相关推荐
星越华夏3 分钟前
python中四种获取文件后缀名的方法
开发语言·python
javajenius20 分钟前
Pixi:用 Rust 重写 Conda 体验的包管理工具
开发语言·其他·rust·conda
神明不懂浪漫21 分钟前
【第二章】Java中的数据类型,运算符与程序逻辑控制
java·开发语言·经验分享·笔记
laowangpython22 分钟前
tokio-rstracing:Rust 可观测性的标准答案
开发语言·后端·其他·rust
傻啦嘿哟28 分钟前
为什么Python没有块级作用域?
开发语言·python
天天代码码天天30 分钟前
OpenCV 5 + PP-OCRv6 + OpenVINO:C# 本地 OCR 推理更快、更稳、更好集成
opencv·c#·openvino
技术小结-李爽38 分钟前
【工具】Shell之Bash、Zsh配置文件的使用
开发语言·bash
壮Sir不壮1 小时前
GO语言——GMP调度模型
linux·开发语言·golang·go·操作系统·线程·协程
枫叶丹41 小时前
【HarmonyOS 6.0】MDM Kit 深度解析:企业级 user_grant 权限集中管理策略
开发语言·华为·harmonyos
鱼子星_1 小时前
C++从零开始系列篇(一):C++入门——命名空间,输入输出与缺省参数
开发语言·c++