Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# A method that will accept any List<enum> and return a string array

There is an incredibly longer story to why I’m actually doing this, so I’m sure there is a better way as an overall approach. I don’t have time to refactor the entire base structure and I want to minimize about 20k lines in the library to a method. What I want to be able to do is take any List<Enum> and return a string[]. My example is below, I’m sure I’m probably missing some sort of reflection. Thanks!

public enum ActivityEnum
    {
        ID,
        ACTIVITYTYPEID,
        CAMPAIGNID,
        BUDGETID,
        LISTID
    }


public enum ActivityAttributeEnum
    {
        ID,
        ACTIVITYID,
        ACTIVITYATTRIBUTE,
        ENABLED,
        CREATEDBY,
        CREATEDDATE,
        LASTUPDATEBY,
        LASTUPDATEDATE
    }


public string[] myStrings(List<activtyEnum> activityEnums)
        {
            var array = new string[activityEnums.Count];
            for (int i = 0; i < activityEnums.Count; i++)
                array[i] = activityEnums[i].ToString();

            return array;

        }

What I’m unsure of is how to accept any enum. In my example I have activityEnum, but I want the method to accept both ActivityAttribtueEnum and ActivityEnum. There are about 600 enums, so a generic way would be great.

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

private string[] GetNames<TEnum>(List<TEnum> enums) where TEnum : Enum
{
    return enums.Select(e => e.ToString()).ToArray();
}

You really ought to declare the parameter as type IEnumerable<TEnum> because that will work with a List<T>, an array, the result of a LINQ query and various other list types too.

Note that any list can have its items converted to a string array in this way too, so there’s not really a need to to constrain the item type to be an enum. It won’t actually hurt to define the method without a generic constraint. You might just want to change the name in that case, because the values returned might not be names.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading