Reputation: 4782
I have an enum with a whole bunch of values (only three shown here):
public enum LookupType
{
Alignment,
Language,
ReEmbedBehavior
}
I then have a method that gets data based on a varchar field called LookupType...what I want is to limit callers of this method to only the lookuptypes that are in the database...so at the end of my WHERE clause, I want the enum name as a string, not the integer value of it.
Callers would then do something like GetLookupsByLookupType(LookupType.Language) and my method would make the call as "where lookuptype = 'Language'"
public List<Lookup> GetLookupsByLookupType(UnicornMedia.Core.DomainModel.Enumerations.LookupType lookupType)
{
var lookups = new List<Lookup>();
string SQL = String.Format(@"Select id, name, value, lookuptype
from lookups
where lookuptype = '{0}'", lookupType.ToString());
...<snip>...
}
It's probably something simple but I seem to bump into this from time to time and instead of figuring it out, I end up just using a Dictionary...anyway, there it is, thanks
Upvotes: 3
Views: 531
Reputation: 19881
Your code should work just fine. I ran the following and the string returned the expected results.
class Program
{
static void Main(string[] args)
{
LookupType lookupType = LookupType.Language;
Console.WriteLine(GetLookupsByLookupType(lookupType));
Console.Read();
}
public static string GetLookupsByLookupType(LookupType lookupType)
{
string SQL = String.Format(@"Select id, name, value, lookuptype from lookups where lookuptype = '{0}'", lookupType.ToString());
return SQL;
}
}
public enum LookupType
{
Alignment,
Language,
ReEmbedBehavior
}
Make sure you are not passing your SQL string as you have it displayed above. Either put the string together on one line, or use the following:
string SQL = String.Format(@"Select id, name, value, lookuptype from " +
"lookups where lookuptype = '{0}'", lookupType.ToString());
Upvotes: 1
Reputation: 17973
Have you tried Enum.GetName?
Actually, the following snippet shows that simply calling ToString
works as well.
enum LookupType {
Language
}
public class Program {
public static void Main(string[] args) {
string str = string.Format("{0}", LookupType.Language);
// str = "Language"
Console.WriteLine(LookupType.Language);
// output: Language
}
}
Upvotes: 2
Reputation: 24713
You do not need GetName...
LookupType.Alignment.ToString();
or
just as you have it in your code...
lookupType.ToString()
Upvotes: 1
Reputation: 55334
You can use the GetName method (http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx):
Enum.GetName(typeof(LookupType), lookupType);
Upvotes: 1
Reputation: 2032
Simply doing a .ToString() will get you the enum name as a string value.
Upvotes: 8
Reputation: 754715
Try the following
string name = System.Enum.GetName(typeof(LookupType), LookupType.Language);
Upvotes: 2