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 列表较大时。
相关推荐
编程零零七27 分钟前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
我爱Jack39 分钟前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
米饭「」40 分钟前
C++AVL树
java·开发语言·c++
心愿许得无限大1 小时前
Qt 常用界面组件
开发语言·c++·qt
2401_858286111 小时前
OS15.【Linux】gdb调试器的简单使用
linux·运维·服务器·开发语言·gdb
牛马baby1 小时前
MATLAB下载安装教程(附安装包)2025最新版(MATLAB R2024b)
开发语言·matlab
shenyan~2 小时前
关于 c、c#、c++ 三者区别
开发语言·c++
Ashlee_code2 小时前
什么是Web3?金融解决方案
开发语言·金融·架构·eclipse·web3·区块链·php
Evand J2 小时前
【MATLAB例程】AOA与TDOA混合定位例程,适用于三维环境、4个锚点的情况,附下载链接
开发语言·matlab
机器视觉知识推荐、就业指导2 小时前
Qt 与Halcon联合开发八: 结合Qt与Halcon实现海康相机采图显示(附源码)
开发语言·数码相机·qt