Md Ghousemohi
Md Ghousemohi

Reputation: 197

c# how to get name based on enum

Here I have small table Like Employee

EmpId   EmpName   EmpType
1       John       1
2       Mick       3
3       Smith      2

I wrote a simple Linq query finding details Like

public Users GetUsers(int Id)
        { var x = from n in db.Users
                    where n.Username == Id
                    select n;
            return x.FirstOrDefault();

        }

when its get result as EmpId=1,EmpName=John,Emptype=1 Insted of 1 i need Admin from enum

 enum TypeofEmp{
            Admin=1,
            HttpRequest=2,
            Devoloper=3
    };

How can i get these values

Upvotes: 0

Views: 87

Answers (2)

Fredrik
Fredrik

Reputation: 2317

Enum.GetValues returns an array of all values;

foreach(var value in Enum.GetValues(typeof(TypeofEmp)))
{
    Console.WriteLine($"{(TypeofEmp)value} (integer value: {(int)value})");
}

// output:
Admin (integer value: 1)
HttpRequest (integer value: 2)
Devoloper (integer value: 3)

Upvotes: 1

Martin Zikmund
Martin Zikmund

Reputation: 39072

You can use Enum.GetName method:

Enum.GetName( typeof( TypeofEmp ), value );

Also, if you want to convert an int value to instance of your enum, you can do simple cast, for example:

var enumInstance = ( TypeofEmp )1;

Upvotes: 4

Related Questions