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 列表较大时。
相关推荐
上单带刀不带妹2 小时前
Node.js 中的 fs 模块详解:文件系统操作全掌握
开发语言·javascript·node.js·fs模块
牵牛老人2 小时前
Qt中的QWebSocket 和 QWebSocketServer详解:从协议说明到实际应用解析
开发语言·qt·网络协议
chenglin0162 小时前
制造业ERP系统架构设计方案(基于C#生态)
开发语言·系统架构·c#
凌晨7点2 小时前
控制建模matlab练习13:线性状态反馈控制器-②系统的能控性
开发语言·matlab
要记得喝水3 小时前
汇编中常用寄存器介绍
开发语言·汇编·windows·c#·.net
shi57833 小时前
C# 常用的线程同步方式
开发语言·后端·c#
凌晨7点3 小时前
控制建模matlab练习11:伯德图
开发语言·matlab
freed_Day4 小时前
Java学习进阶--集合体系结构
java·开发语言·学习
Shun_Tianyou4 小时前
Python Day25 进程与网络编程
开发语言·网络·数据结构·python·算法
嫩萝卜头儿4 小时前
从零掌握 Java AWT:原理、实战与性能优化
java·开发语言·性能优化