C# 智能枚举:优化版

发布: (2026年1月2日 GMT+8 10:12)
2 min read
原文: Dev.to

Source: Dev.to

问题:LINQ 税

在第 1 部分我们用记录(record)取代了魔法数字。要查找特定状态时我们使用了 LINQ:

var status = Status.All.SingleOrDefault(x => x.Id == productStatusId);

虽然这样可行,但它有两个缺点:

  • 复杂度 – 每次需要获取状态时都必须重复 LINQ 逻辑。
  • 性能 – LINQ 执行线性搜索 O(n)。在高流量应用中,若状态集合很大,这会带来不必要的开销。

我们可以通过在 Status 类内部添加一个私有 Dictionary 来优化,使得无论状态有多少,都能实现瞬时的 O(1) 查找。

public record StatusValue(int Id, string Description);

public static class Status
{
    public static readonly StatusValue Pending     = new(1, "Pending Approval");
    public static readonly StatusValue Available   = new(2, "Available for Sale");
    public static readonly StatusValue OutOfStock = new(3, "Out of Stock");

    public static readonly StatusValue[] All = { Pending, Available, OutOfStock };

    private static readonly Dictionary _lookup = All.ToDictionary(s => s.Id);

    // O(1) access to the full object
    public static StatusValue? Get(int id) => _lookup.GetValueOrDefault(id);

    // Quick existence check
    public static bool Exists(int id) => _lookup.ContainsKey(id);

    // Accessing properties
    public static string GetDescription(int id) => Get(id)?.Description ?? "Unknown";
}

用法

不再需要编写 LINQ 查询,服务现在可以这样做:

if (Status.Exists(userInputId))
{
    var label = Status.GetDescription(userInputId);
    Console.WriteLine($"Processing: {label}");
}

其他资源

  • Live Demo – 在 .NET Fiddle 上尝试
  • Source Code – 查看 GitHub Gist
  • Dictionary 类文档 – 在官方 .NET 文档 中了解更多关于 O(1) 查找引擎的信息。

Version Note: 这些性能优化针对 .NET 6+ 环境设计。

Back to Blog

相关文章

阅读更多 »

C# Smart Enums:高级

封面图片:C Smart Enums:advanced https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-upload...

MiniScript 2026 路线图

2026 展望 随着 2025 接近尾声,是时候展望 2026 了!MiniScript 已经八岁。许多编程语言真的进入了它们的……