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

C#中按属性值过滤嵌套字典的更优实现方案探讨

多层嵌套字典过滤的优化方案

你需要过滤C#中Dictionary<int, Dictionary<int, Dictionary<int, location1>>>结构,筛选出location1.Id == 3的条目,以下是针对可读性和执行效率的优化方案:

相关类定义

public class Location 
{
    public Dictionary<int, Dictionary<int, Dictionary<int, location1>>> Example { get; set; }
}

public class location1
{
    public int Id { get; set; }
    public string Name { get; set; }
}

现有实现代码

var filteredLocations = locations.Select(location =>
    {
        var filteredDict = location
            .Example
            .ToDictionary(
                outerKey => outerKey.Key,
                outerValue => outerValue.Value
                    .ToDictionary(
                        middleKey => middleKey.Key,
                        middleValue => middleValue.Value
                            .Where(innerEntry => innerEntry.Value.Id == 3)
                            .ToDictionary(innerKey => innerKey.Key, innerValue => innerValue.Value)
                    )
            );
        location.Example = filteredDict;
        return new Location(location);
    })
    .ToList();

优化方案

一、提升可读性:拆分逻辑为独立方法

把每层字典的过滤逻辑封装成单一职责的方法,让主代码逻辑清晰易懂,后续维护也更方便:

// 过滤最内层字典:保留指定Id的location1
private static Dictionary<int, location1> FilterInnerDict(Dictionary<int, location1> innerDict, int targetId)
{
    return innerDict.Where(entry => entry.Value.Id == targetId)
                   .ToDictionary(entry => entry.Key, entry => entry.Value);
}

// 过滤中间层字典:处理内层字典并移除空条目
private static Dictionary<int, Dictionary<int, location1>> FilterMiddleDict(Dictionary<int, Dictionary<int, location1>> middleDict, int targetId)
{
    return middleDict.Select(entry => new { entry.Key, FilteredInner = FilterInnerDict(entry.Value, targetId) })
                   .Where(item => item.FilteredInner.Any()) // 移除空的内层字典
                   .ToDictionary(item => item.Key, item => item.FilteredInner);
}

// 过滤最外层字典:处理中间层字典并移除空条目
private static Dictionary<int, Dictionary<int, Dictionary<int, location1>>> FilterOuterDict(Dictionary<int, Dictionary<int, Dictionary<int, location1>>> outerDict, int targetId)
{
    return outerDict.Select(entry => new { entry.Key, FilteredMiddle = FilterMiddleDict(entry.Value, targetId) })
                   .Where(item => item.FilteredMiddle.Any()) // 移除空的中间层字典
                   .ToDictionary(item => item.Key, item => item.FilteredMiddle);
}

主调用代码会变得非常简洁:

var filteredLocations = locations.Select(loc => 
{
    var filteredExample = FilterOuterDict(loc.Example, 3);
    return new Location { Example = filteredExample };
}).ToList();

二、优化执行效率:过滤空层级

原有实现会保留所有外层和中层字典,哪怕内层过滤后是空的。上面的辅助方法通过.Where(item => item.FilteredInner.Any())和.Where(item => item.FilteredMiddle.Any()),自动移除没有有效条目的层级,减少不必要的内存占用,同时让结果更精简。

三、可选:封装为扩展方法(复用场景)

如果这类过滤逻辑在项目中多次使用,可以改成扩展方法,调用更自然:

public static class DictionaryExtensions
{
    public static Dictionary<int, location1> FilterLocation1ById(this Dictionary<int, location1> innerDict, int targetId)
    {
        return innerDict.Where(entry => entry.Value.Id == targetId)
                       .ToDictionary(entry => entry.Key, entry => entry.Value);
    }

    public static Dictionary<int, Dictionary<int, location1>> FilterMiddleLayer(this Dictionary<int, Dictionary<int, location1>> middleDict, int targetId)
    {
        return middleDict.Select(entry => new { entry.Key, FilteredInner = entry.Value.FilterLocation1ById(targetId) })
                       .Where(item => item.FilteredInner.Any())
                       .ToDictionary(item => item.Key, item => item.FilteredInner);
    }

    public static Dictionary<int, Dictionary<int, Dictionary<int, location1>>> FilterOuterLayer(this Dictionary<int, Dictionary<int, Dictionary<int, location1>>> outerDict, int targetId)
    {
        return outerDict.Select(entry => new { entry.Key, FilteredMiddle = entry.Value.FilterMiddleLayer(targetId) })
                       .Where(item => item.FilteredMiddle.Any())
                       .ToDictionary(item => item.Key, item => item.FilteredMiddle);
    }
}

调用示例:

var filteredLocations = locations.Select(loc => 
{
    var filteredExample = loc.Example.FilterOuterLayer(3);
    return new Location { Example = filteredExample };
}).ToList();

这种实现既提升了可读性,每个方法只负责单一逻辑,又通过过滤空层级优化了效率,后续修改过滤条件(比如改为Id=5)只需调整参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:53:27