0

Let's say item.Products is "1,3" and I have enum Products

public enum Products
{
    [Description("Product A")]
    ProductA = 1,
    [Description("Product B")]
    ProductB = 2,
    [Description("Product C")]
    ProductC = 3
}

How do I convert from "1,3" to "ProductA, ProductC"?

3
  • 2
    string.Join(", ", input.Split(',').Select(x => (Products)int.Parse(x))) ? Commented May 19, 2021 at 9:53
  • @canton7 if I want to get "Product A" instead, how do I do it? Commented May 19, 2021 at 10:01
  • 1
    With reflection -- see stackoverflow.com/questions/1799370/… Commented May 19, 2021 at 10:04

4 Answers 4

2

Split and use GetName of the Enum, after that join with string.join

string.Join(",", input.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
   .Select(x=>Enum.GetName(typeof(Products), int.Parse(x))))
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your solution but it doesn't get what I need. It is still getting "ProductA,ProductB" instead of "Product A, Product B".
1

The others have given you good answers. If you want a more elegant way to do it though (imho), you could try install a NuGet package of mine: https://www.nuget.org/packages/Extenso.Core/

and then use it like this:

string values = "1,3";
string result = string.Join(", ", values.Split(',').ToListOf<int>().Select(x => EnumExtensions.GetDisplayName(((Products)x))));
Console.WriteLine(result);

With these usings:

using Extenso;
using Extenso.Collections;

You should definitely choose one of the others as the answer, as they don't require NuGet packages. That said, you can find the source code for this on GitHub: https://github.com/gordon-matt/Extenso/

2 Comments

I would try not to depends on third party library unless really needed...anyway thanks.
@Steve Indeed, that's why I told you to choose another as answer and also gave you the link to the source code in case you're interested.
0

Thanks to canton7

The solution is first split the input by comma, then cast it into enum and store into IEnumerable. Then use extension class to get the description name and store into array. Lastly join the array into a string.

IEnumerable<Products> productSplit = item.Products.Split(',').Select(x => (Products)int.Parse(x));
string[] productArray = productSplit.Select(p=>p.ToName()).ToArray();
string products = string.Join(", ", productArray);

and extension class

public static class MyEnumExtensions
{        
    // This extension method is broken out so you can use a similar pattern with 
    // other MetaData elements in the future. This is your base method for each.
    public static T GetAttribute<T>(this Products value) where T : Attribute
    {
        var type = value.GetType();
        var memberInfo = type.GetMember(value.ToString());
        var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
        return attributes.Length > 0
          ? (T)attributes[0]
          : null;
    }

    // This method creates a specific call to the above method, requesting the
    // Description MetaData attribute.
    public static string ToName(this Products value)
    {
        var attribute = value.GetAttribute<DescriptionAttribute>();
        return attribute == null ? value.ToString() : attribute.Description;
    }

}

Comments

0

@Steve - Here is the Class and Conversion code. You also also assign different integer values to enum (not in sequence) and it will work like charm.

public enum Products
{
    [Description("Product A")]
    ProductA = 1,
    [Description("Product B")]
    ProductB = 2,
    [Description("Product C")]
    ProductC = 3
}

Conversion

string numericOutput = $" {(int)Products.ProductA}, {(int)Products.ProductB}, {(int)Products.ProductC}";
Console.WriteLine(numericOutput); // 1, 2, 3

string enumOutput = $" {(Products)1}, {(Products)2}, {(Products)3}";
Console.WriteLine(enumOutput);//ProductA, ProductB, ProductC

Dynamically handling of inputs

for (int i = 0; i < 5; i++)
{
    Products products;
    if (Enum.TryParse(i.ToString(), true, out products) && Enum.IsDefined(typeof(Products), products))
        Console.WriteLine("Converted '{0}' to {1}", i.ToString(), products.ToString());
    else
        Console.WriteLine("{0} is not a value of the enum", i.ToString());
}

//output

0 is not a value of the enum

Converted '1' to ProductA

Converted '2' to ProductB

Converted '3' to ProductC

4 is not a value of the enum

2 Comments

If I have 10 products, then I have to hardcode 10 times?
@steve it is just an example, you can make it based on input through a variable also. I am also adding more code, please check above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.