Enum: you need to get the name of the enumeration, not its int value, like a string

I have an enumeration with a range of values ​​(only three are shown here):

public enum LookupType
{
   Alignment,
   Language,
   ReEmbedBehavior
}

Then I have a method that receives data based on a varchar field called LookupType ... I want to restrict callers to this method only with lookupty types that are in the database ... so at the end of my WHERE, I want The enumeration name was a string, not an integer value.

Then callers will do something like GetLookupsByLookupType (LookupType.Language), and my method will make a call "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>...                                         
        }

, - , , , , , , ... , ,

+3
6

.ToString() .

+8

Enum.GetName?

, , ToString .

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
    }
}
+2

string name = System.Enum.GetName(typeof(LookupType), LookupType.Language);
+2

GetName (http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx):

Enum.GetName(typeof(LookupType), lookupType);
+1

GetName...

LookupType.Alignment.ToString();

, ...

lookupType.ToString()
+1

Your code should work fine. I did the following and the line 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 that you do not pass the SQL string as shown in the figure above. Either concatenate the string on one line, or use the following:

        string SQL = String.Format(@"Select id, name, value, lookuptype from " + 
            "lookups where lookuptype = '{0}'", lookupType.ToString());
+1
source

Source: https://habr.com/ru/post/1778411/


All Articles