c# - 适当的 c# 集合,用于通过多个键进行快速搜索

标签 c# algorithm design-patterns data-structures collections

您好,我正在重构一些遗留代码。有一些代码表示从自定义类型到 C# 类型的“转换器”。

          ...
           if (dataType == CustomType.Bit)
            {
                return typeof(bool);
            }
            else if (dataType == CustomType.Bittype ||
                dataType == CustomType.Char ||
                dataType == CustomType.Fromtotype ||
                dataType == CustomType.Mdcintervaltype ||
                dataType == CustomType.Nclob ||
                dataType == CustomType.Nchar ||
                dataType == CustomType.Ntext ||
                dataType == CustomType.Nvarchar ||
                dataType == CustomType.Nvarchar2 ||
                dataType == CustomType.Varchar ||
                dataType == CustomType.Varchar2)
            {
                return typeof(string);
            }
            else if (dataType == CustomType.Date ||
                dataType == CustomType.Datetime ||
                dataType == CustomType.Timestamp3 ||
                dataType == CustomType.Timestamp6)
            {
                return typeof(DateTime);
            }
            else if (dataType == CustomType.Decimal ||
                dataType == CustomType.Money ||
                dataType == CustomType.Number ||
                dataType == CustomType.Numeric)
            {
                return typeof(decimal);
            }

...

问:我正在寻找一些 C# 结构(集合或非集合)来帮助我使用一对多关系进行快速搜索。 (即我想要类似的东西 { Collection possible keys} ==> { value }

P.s 我认为每个 Custromtype 都是键并返回相同类型的简单字典并不“漂亮”

new Dictionary<string, Type>()(){
    { CustomType.Bittype, typeof(string)},
    { CustomType.Fromtotype, typeof(string)}
     ...
    { CustomType.Datetime,  typeof(DateTime)},
    { CustomType.Date, typeof(DateTime)}
    ....
}

最佳答案

如果您将 string 作为默认类型,您可以使 Dictionary漂亮;另一个建议是将其实现为扩展方法

 public static class CustomTypeExtensions {
   private static Dictionary<CustomType, Type> s_Map = new Dictionary<CustomType, Type>() {
     {CustomType.Datetime,  typeof(DateTime)},
     {CustomType.Date, typeof(DateTime}, 
     ...
   }; 

   public static Type ToType(this CustomType value) {
     if (s_Map.TryGetValue(value, out var result))
       return result;
     else
       return typeof(string); // when not found, return string 
   }
 }

....

var custom = CustomType.Bittype;

...

Type t = custom.ToType();   

关于c# - 适当的 c# 集合,用于通过多个键进行快速搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48761725/

相关文章:

java - 为什么jaxb会生成这样的代码?

c# - 将 Json 字符串从 MVC 操作反序列化为 C# 类

c# - 序列化无符号整数 (ulong) 数组时 Json.NET 崩溃

algorithm - 快速实现 FNV 哈希

java - 从多个相关的 excel 表中读取 excel 数据并转储到 java 类中

c++ - 给定一个数 N,有多少对数的平方和小于或等于 N?

C# 在 Control 的生命周期中 Site (ISite) 不为空?

c# - .Net 位图类构造函数 (int, int) 和 (int, int, PixelFormat) 在非常好的参数上抛出 ArgumentException

swift - 如何在Swift中美化缓存 "pattern"?

php - 这是装饰器模式(PHP)吗?