How to elegantly compare an enum to a DataTable cell?
In our application we work with DataTable
s a lot. This is dictated by the interface to a another system. Often a column in one of these DataTable's is in fact an enumeration, which is then of a Int16
datatype. Currently we use magic constants all over the place, but that isn't pretty. A real enum would be much better, but how can you write an elegant comparison? Especially considering that a DBNull
is also sometimes a valid value.
Ideally we would write this:
if ( tbl.Rows[0]["EnumColumn"] == MyEnum.SomeValue )
// Do stuff
But, naturally, that will not work. The closest to what I can come is:
if ( tbl.Rows[0]["EnumColumn"] != DBNull.Value && Convert.ToInt32(tbl.Rows[0]["EnumColumn") == (int)MyEnum.SomeValue )开发者_开发技巧
// DO stuff
Which looks plain ugly. Any ideas on how to make this prettier and easier to write?
It should be something like this:
tbl.Rows[0]["EnumColumn"] != DbNull.Value && Convert.ToInt32(tbl.Rows[0]["EnumColumn"]) == MyEnum.SomeValue
I would make a static method for it:
public enum TestEnum
{
A = 1,
B = 2
}
public static bool EqualsTestEnum(object value, TestEnum enumValue)
{
if (value == null || value == DBNull.Value)
{
return false;
}
int i;
if (int.TryParse(value.ToString(), out i))
{
return i == (int) enumValue;
}
return false;
}
精彩评论