You need to enable JavaScript to run this app. C#中如何实现可通过ID/名称便捷查询的多对象存储?
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何实现可通过ID/名称便捷查询的多对象存储?

C# 实现结构化物品存储与便捷查询的方案

核心思路

不要用原生二维数组做这类结构化多字段数据存储——这类存储会带来类型混乱、查询效率低、维护成本高的问题。C# 下最优方案是强类型实体定义 + 双向唯一索引字典,完全匹配你提出的“ID/名称唯一、通过任意一个键快速查全属性、支持类静态方式便捷调用”的需求。

具体实现步骤

1. 定义物品的结构化实体

替代二维数组的字符串拼接式存储,每个字段保留对应的数据类型,避免频繁的类型转换错误:

// 单个物品的结构化类型定义
public class ItemInfo
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; } // 价格推荐用decimal,若需整数可直接替换为int
    public string Location { get; set; }
}

2. 实现静态访问类

内置两个字典做双向索引(一个按ID做键、一个按名称做键),保证唯一值查询的效率是O(1),不用循环遍历所有数据:

public static class Item
{
    // 双向索引字典:保证ID、Name两个唯一值的快速查询
    private static readonly Dictionary<int, ItemInfo> _itemIndexById = new();
    private static readonly Dictionary<string, ItemInfo> _itemIndexByName = 
        new(StringComparer.OrdinalIgnoreCase); // 名称匹配默认忽略大小写,适配日常使用习惯

    /// <summary>
    /// 初始化物品数据,程序启动时调用一次即可
    /// </summary>
    public static void LoadItems()
    {
        _itemIndexById.Clear();
        _itemIndexByName.Clear();

        // 直接录入你的示例数据
        AddItem(1, "Apple", 10, "Storage");
        AddItem(2, "Bread", 20, "Outside");
        AddItem(3, "TV", 30, "House");
    }

    // 内部辅助方法:添加物品时自动同步两个索引,避免数据不同步
    private static void AddItem(int id, string name, decimal price, string location)
    {
        // 校验唯一值约束,避免重复录入冲突
        if (_itemIndexById.ContainsKey(id)) 
            throw new InvalidOperationException($"重复录入的物品ID:{id}");
        if (_itemIndexByName.ContainsKey(name)) 
            throw new InvalidOperationException($"重复录入的物品名称:{name}");

        var item = new ItemInfo
        {
            ID = id,
            Name = name,
            Price = price,
            Location = location
        };
        _itemIndexById.Add(id, item);
        _itemIndexByName.Add(name, item);
    }

    // 完全匹配你期望的调用方法逻辑
    /// <summary>
    /// 按物品名称查询对应ID
    /// </summary>
    public static int ID(string itemName)
    {
        if (_itemIndexByName.TryGetValue(itemName, out var item))
            return item.ID;
        throw new KeyNotFoundException($"未找到名称为 {itemName} 的物品");
    }

    /// <summary>
    /// 按物品ID查询对应名称
    /// </summary>
    public static string Name(int itemId)
    {
        if (_itemIndexById.TryGetValue(itemId, out var item))
            return item.Name;
        throw new KeyNotFoundException($"未找到ID为 {itemId} 的物品");
    }

    /// <summary>
    /// 按物品ID查询对应价格
    /// </summary>
    public static decimal Price(int itemId)
    {
        if (_itemIndexById.TryGetValue(itemId, out var item))
            return item.Price;
        throw new KeyNotFoundException($"未找到ID为 {itemId} 的物品");
    }

    /// <summary>
    /// 按物品ID查询对应存放位置
    /// </summary>
    public static string Location(int itemId)
    {
        if (_itemIndexById.TryGetValue(itemId, out var item))
            return item.Location;
        throw new KeyNotFoundException($"未找到ID为 {itemId} 的物品");
    }

    /// <summary>
    /// 便捷方法:按ID直接拿到物品的全量属性,无需逐字段调用
    /// </summary>
    public static ItemInfo GetItem(int itemId)
    {
        if (_itemIndexById.TryGetValue(itemId, out var item))
            return item;
        throw new KeyNotFoundException($"未找到ID为 {itemId} 的物品");
    }
}

3. 实际调用示例

完全对齐你写的调用逻辑:

// 程序启动时先加载一次物品数据
Item.LoadItems();

// 你期望的调用方式全部可正常运行
int IID = Item.ID("Bread"); // 通过名称拿到对应ID
string IName = Item.Name(2); // 通过ID拿到对应名称
decimal IPrice = Item.Price(IID); // 通过ID拿到对应价格
string ILocation = Item.Location(IID); // 通过ID拿到对应存放位置

// 也可以一次拿到全量属性,减少重复代码
var breadItem = Item.GetItem(IID);
// 直接用 breadItem.Name、breadItem.Price 等属性即可

方案对比

  • 相比原生二维数组:不存在混合类型存储需要反复拆包、类型转换的问题,查询时不需要逐行循环匹配,数据量越大性能优势越明显。
  • 支持后续扩展:如果需要动态增删物品、从数据库/配置文件加载数据,只要在Item静态类里补充对应的增删逻辑,自动维护两个字典的索引即可,不需要改动业务调用的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 05:06:06