I'm pulling some data from a table using LINQ 2 SQL...one of the pieces of data is a value that represents an enumation in my application code.
What is the simplest way to make a comparison between the data returned in LINQ objects and the enumeration in the application code. So for example
enum SomeEnum
{
First
Second
}
then in the method I have
Table<LinqObject> objects = dc.GetTable<LinqObject>();
foreach (var item in objects)
{
// What's the simplest way to do this comparison???
if (item.SomeNullableInteger == SomeEnum.First) // Note I realise this doesn't work!!!
{
// Do something...
}
}
I could do this
SomeEnum.First.Equals(item.SomeNullableInteger)
or I could store the enumeration names in the database and then i'd be able to do this
Enum.GetName(SomeEnum, SomeEnum.First) == item.SomeNullableName
is there a better way? The enum only has two items and they're pretty fixed...could maybe have a third or a fourth but will probably never grow beyond that. So having a whole table seems like overkill.
Actually this is a duplicate of C# int to enum conversion
to have
to work:
This should work as expected - just cast to the base type.
UPDATE
The best and cleanest solution is probably to update your DBML file.
Type
of the selected property fromSystem.Int32
to something likeglobal::SomeNamespace.SomeEnum
. Maybe it will work without theglobal
qualifier, but I am not sure.Now, if the code is regenerated, the property will be of the enumeration type instead of a integer. If you have nullable properties, you must of course use a nullable enumeration type.
Casting the enum to an int should do the trick.
You could cast the
Enum
toint
:According to the official documentation, you could cast your enum as an int to compare.
http://msdn.microsoft.com/en-us/library/sbbt4032.aspx
For code clarity, it might be helpful to declare your enum as