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

.NET Core 8:如何用LINQ筛选字典含指定值的Foo对象?

筛选字典包含指定键值对的Foo对象列表

我需要实现一个方法,接收Foo对象列表,其中Foo包含一个Dictionary<string, object>类型的属性(object存储string、int、double等原始类型),目标是筛选出字典中包含指定键值对的Foo对象。我尝试的代码如下:

public List<Foo> FindFoos(List<Foo> foos, string itemKey, object itemValue) {
    List<Foo> found = foos.Where(f => f.TheDict[itemKey] == itemValue).ToList();
    return found;
}

调用示例:

var a = FindFoos(foos, "name", "Something");
var b = FindFoos(foos, "age", 45);

现有代码的问题

  • 当字典中不存在itemKey时,直接通过索引访问会抛出KeyNotFoundException
  • 对于值类型(如int、double),装箱后使用==比较可能因引用不同导致结果错误(例如超出-128到127范围的int,装箱后是不同对象实例)

修正后的代码

public List<Foo> FindFoos(List<Foo> foos, string itemKey, object itemValue)
{
    return foos.Where(f => f.TheDict.TryGetValue(itemKey, out var value) && object.Equals(value, itemValue)).ToList();
}

说明

  • TryGetValue方法会先检查键是否存在,存在则返回对应值,避免抛出异常
  • object.Equals会正确处理值类型装箱后的内容比较,同时也能兼容string等引用类型的值比较逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:25:03