Momen Alnaser
Momen Alnaser

Reputation: 85

find string from enum

I have tried to below suggestions but nothing works, and I have edited the code to be easier. the purpose of this code is to get the row of the data based on the enum.

For example: if I give the value "bra" for search, then the wanted result should be brazil from enum but since the enum is an int then it's like I'm saying select the data where location = 3 if we suppose that brazil =3 in the enum.

public LocationType Location { get; set; }
    
public enum LocationType
{
    brazil,
    USA,
    UK
} 
public async Task<IActionResult> Index(string id, [FromForm] string search)

if (!string.IsNullOrWhiteSpace(search))
{
    result = applicationDbContext.Where(x => x.Location.ToString().Contains(search)).ToList();
}

note: search is string input.

Upvotes: 1

Views: 792

Answers (3)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

If you want to get the numeric values (or enum values) of those that matches the search you can do it like below:

public async Task<IActionResult> Index(string id, [FromForm] string search)

if (!string.IsNullOrWhiteSpace(search))
{
     List<LocationType> locations = Enum.GetNames(typeof(LocationType))
               .Where(x => x.ToLower().Contains(search.ToLower()))
               .Select(x => Enum.Parse<LocationType>(x))
               .ToList();

     result = applicationDbContext.Where(x => locations.Contains(x.Location)).ToList();
}

Upvotes: 1

Rezaeimh7
Rezaeimh7

Reputation: 1545

Converting your Enum to string:

 Location.ToString();    //output = A

But This converts your Enum to a string containing all members:

string[] locs= Enum.GetNames(typeof(LocationType ));

which can be used in your query.

Upvotes: 1

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

(char)locs does definitly not what you expect it does. An enum is nothing but an int, and thus it can be directly converted to a char. But (char)1 is not the letter A, but an ASCII-control-code. The letter A has the code 65, though.

So you have a couple of opportunities:

  1. make your enum start at 65:

    public enum LocationType
    {
        A = 65,
        B = 66,
        C = 67,
        K = 75
    }
    

    Now when you convert the enum to char you´d get A for example.

  2. Use enum.ToString(), e.g. LocationType.C.ToString() returns "C".

  3. The better idea however is to use the built-in functionality to get an enums name as m.r226 pointed out in his answer.

Upvotes: 0

Related Questions