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

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

方法 1: 使用 LINQ 的 Any 方法

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 方法

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),这样会提高查找效率。

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 列表较大时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好玩的Matlab(NCEPU)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值