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 列表较大时。
相关推荐
sinat_3671045620 小时前
WPF 常用控件
c#·xaml·控件·wfp
上弦月-编程20 小时前
Java类与对象:编程核心解密
java·开发语言·jvm
大大杰哥20 小时前
从 Volatile 到 ThreadLocal:Java 线程安全机制备忘
java·开发语言·jvm
Artech20 小时前
[对比学习LangChain和MAF-03]完全不同的Agent设计哲学
python·ai·langchain·c#·agent·maf
崇山峻岭之间20 小时前
matlab绘制复杂曲线
开发语言·matlab
skywalk816321 小时前
中文编程语言的开创性语法,言律:一门以汉语为思维内核的原生中文编程语言
开发语言·编程
宠..21 小时前
VS Code SSH 远程连接 Ubuntu 并实现快速运行(C/C++示例)
java·运维·c语言·开发语言·c++·ubuntu·ssh
Omics Pro21 小时前
免费!糖蛋白质组学数据分析
开发语言·深度学习·数据挖掘·数据分析·r语言·excel·知识图谱
枫叶林FYL21 小时前
【强化学习】2 大规模并行强化学习中的耦合策略优化:受控多样性驱动的样本高效探索
开发语言·php
chao18984421 小时前
基于MATLAB的音频信号AM调制与解调实现
开发语言·matlab·音视频