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

如何编写LINQ where查询筛选同时匹配字典双值的集合条目

LINQ筛选多字段匹配条目的实现方案

前置准备

首先将待匹配的<code, qty>键值对存储为HashSet结构,相比普通List可将匹配查询的时间复杂度从O(n)降到O(1),数据量大时性能优势更明显。

基础代码定义

// 实体类定义
public class FakeClass
{
    public int code { get; set; }
    public int qty { get; set; }
}

// 测试数据源构造
List<FakeClass> collection = new List<FakeClass>
{
    new FakeClass { code = 1, qty = 1 },
    new FakeClass { code = 2, qty = 2 },
    new FakeClass { code = 3, qty = 1 },
    new FakeClass { code = 1, qty = 3 }
};

// 待匹配键值对集合
HashSet<(int code, int qty)> matchPairs = new HashSet<(int code, int qty)>
{
    (1,1),
    (1,2),
    (1,3)
};

核心查询逻辑

两种常用写法均可实现需求,返回结果一致:

写法1:方法语法(简洁直观)

var result = collection.Where(item => matchPairs.Contains((item.code, item.qty))).ToList();

写法2:关联查询(适合多数据源关联场景)

var result = (from item in collection
             join pair in matchPairs
             on new { item.code, item.qty } equals new { pair.code, pair.qty }
             select item).ToList();

低版本C#兼容方案

如果C#版本低于7.0不支持值元组,可将匹配集合替换为HashSet<Tuple<int, int>>,逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:27:00