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 列表较大时。
相关推荐
程序媛小盐4 分钟前
Java基础编程练习第34题-正则表达式
java·开发语言·正则表达式
炬火初现5 分钟前
Go语言的基础类型
开发语言·后端·golang
程序员老冯头13 分钟前
第七节 MATLAB数据类型
开发语言·前端·数据结构·python·算法·matlab·信息可视化
ling__wx23 分钟前
List、Set 和 Map 的区别及常见实现类、线程安全集合(总结图表)
java·list·set·map·集合·线程安全
小胖墩有点瘦28 分钟前
基于Python+Django的二手房信息管理系统
开发语言·python·django
Tee xm32 分钟前
清晰易懂的 Swift 安装与配置教程
开发语言·ios·swift
JKHaaa1 小时前
头歌 JAVA 桥接模式实验
java·开发语言·桥接模式
江沉晚呤时1 小时前
桥接模式(Bridge Pattern)在 .NET Core 中的实现
java·开发语言·后端·c#·.netcore·net
tt5555555555551 小时前
嵌入式面经-C语言:智能指针,`#define` 和 `const`,`typedef`,头文件中定义静态变量
c语言·开发语言·c++
马小学编程1 小时前
Python元组
开发语言·笔记·python·学习·职场发展