Reputation: 1504
Hello i'm working on refactoring some legacy code. There some code that represents something like "converter" from custom type to c# type.
...
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);
}
...
Q: I'm looking for some C# structure (collection or not) that would be able to help me with fast search with one to many relonships. (i.e i would like something that look like { Collection possible keys} ==> { value }
P.s I think that simple Dictionary where each Custromtype is key and return the same type isn't "beatiful"
new Dictionary<string, Type>()(){
{ CustomType.Bittype, typeof(string)},
{ CustomType.Fromtotype, typeof(string)}
...
{ CustomType.Datetime, typeof(DateTime)},
{ CustomType.Date, typeof(DateTime)}
....
}
Upvotes: 1
Views: 82
Reputation: 572
Dmitry's approach is fine, also you can use something like this:
class Example
{
private readonly HashSet<CustomType> _stringCompatibleTypes = new HashSet<CustomType>
{
CustomType.Char, CustomType.Fromtotype, CustomType.Nclob, ...
};
private readonly HashSet<CustomType> _dateCompatibleTypes = new HashSet<CustomType>
{
CustomType.Datetime, CustomType.Timestamp3, CustomType.Timestamp6, ...
};
// Another type sets
public Type Foo(CustomType dataType)
{
if (_stringCompatibleTypes.Contains(dataType))
{
return typeof(string);
}
if (_dateCompatibleTypes.Contains(dataType))
{
return typeof(DateTime);
}
...
}
}
Upvotes: 0
Reputation: 186668
You can make Dictionary
a bit more beautiful if you put string
as a default type; another suggestion is to implement it as an extension method
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();
Upvotes: 7