You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取两个同类型对象列表中Month和ISSPA属性值相同的项?

筛选两个列表中Month和ISSPA属性均匹配的项

假设我们有如下实体类:

public class X
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Month { get; set; }
    public string ISSPA { get; set; }
}

方法1:使用LINQ Join直接关联匹配项

通过Join方法可以一次性获取两个列表中匹配的元素对,也能分别提取两个列表中的匹配项:

// 初始化示例数据
var list1 = new List<X>
{
    new X { Id = 1, Name = "John", Month = "October", ISSPA = "1234" },
    new X { Id = 2, Name = "Ryan", Month = "September", ISSPA = "1234" }
};

var list2 = new List<X>
{
    new X { Id = 1, Name = "Chris", Month = "September", ISSPA = "1234" }
};

// 获取两个列表中匹配的元素对
var matchedPairs = list1.Join(
    list2,
    item1 => new { item1.Month, item1.ISSPA }, // list1的匹配键
    item2 => new { item2.Month, item2.ISSPA }, // list2的匹配键
    (item1, item2) => new { List1Item = item1, List2Item = item2 }
);

// 提取list1中的匹配项
var matchedFromList1 = matchedPairs.Select(p => p.List1Item).ToList();
// 提取list2中的匹配项
var matchedFromList2 = matchedPairs.Select(p => p.List2Item).ToList();

运行后,matchedFromList1会包含List1的Item2,matchedFromList2会包含List2的Item1,完全符合需求。

方法2:使用Where+Any分别筛选

如果需要单独从每个列表中筛选出存在匹配项的元素,用Where结合Any的逻辑更直观:

// 从list1中筛选:存在list2中Month和ISSPA都相同的项
var matchedList1 = list1.Where(item1 => 
    list2.Any(item2 => item2.Month == item1.Month && item2.ISSPA == item1.ISSPA)
).ToList();

// 从list2中筛选:存在list1中Month和ISSPA都相同的项
var matchedList2 = list2.Where(item2 => 
    list1.Any(item1 => item1.Month == item2.Month && item1.ISSPA == item2.ISSPA)
).ToList();

性能优化(大数据量场景)

如果列表数据量较大,方法2的Any会有O(n*m)的时间复杂度,推荐先将其中一个列表的匹配键存入哈希集合来优化:

// 先构建list2的匹配键哈希集合
var list2Keys = new HashSet<(string Month, string ISSPA)>(list2.Select(item => (item.Month, item.ISSPA)));

// 筛选list1的匹配项
var optimizedMatchedList1 = list1.Where(item => list2Keys.Contains((item.Month, item.ISSPA))).ToList();

这种方式能大幅提升大数据量下的查询效率。

额外说明

如果需要忽略字符串大小写匹配,可将比较逻辑改为String.Equals(item1.Month, item2.Month, StringComparison.OrdinalIgnoreCase)。

内容的提问来源于stack exchange,提问作者iMSn20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:20:48