Check Is Enum Description Contains String Value Or Not In C#?

In this article, we will learn how to check is enum description contains string value or not in C#?

In my recent project I got the requirement where I have to check that given string is available in enum list or not but the challenge is I have to match the string with enum description, not enum value. So I found and implement generic method to achieve this, let’s follow the steps as given below to check is enum description contains given string value or not in C#.

First create Countries enum as given below or you can use yours enum if any.

using System.ComponentModel;

namespace Enum_Description_Contains
{
    public enum Countries
    {
        [Description("India")]
        FourPX,

        [Description("China")]
        China,

        [Description("Pakistan")]
        Pakistan,

        [Description("US")]
        US,

        [Description("Canada")]
        Canada
    }
}

Then create the Helper.cs file and add the code to it.

using System;
using System.ComponentModel;

namespace Enum_Description_Contains
{
    public static class Helper
    {
        public static string GetDisplayName<T>(object enumValue)
        {
            string displayName = string.Empty;
            if (enumValue != null)
            {
                var memberInfo = typeof(T).GetMember(Enum.GetName(typeof(T), enumValue))[0];
                var attribute = memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false)[0];
                displayName = ((DescriptionAttribute)attribute).Description;
            }
            return displayName;
        }
    }
}

Now you can use below code to check that given string is available in Countries enum list or not.

using System;
using System.Linq;

namespace Enum_Description_Contains
{
    class Program
    {
        static void Main()
        {
            var countries = Enum.GetValues(typeof(Countries))
                .Cast<Countries>()
                .Select(x => Helper.GetDisplayName<Countries>(x))
                .ToList();

            Console.WriteLine(countries.Contains("India"));
            Console.WriteLine(countries.Contains("Dubai"));
        }
    }
}

Output

You can just use this code to get list of enum description.

var countries = Enum.GetValues(typeof(Countries))
    .Cast<Countries>()
    .Select(x => Helper.GetDisplayName<Countries>(x))
    .ToList();

 

As we can see instead of writing more lines of code we can just use this generic method to check is enum description contains given string value or not in C#. Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Creating Model For Existing Database Using Database First Approach In ASP.NET Core

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories