cadsharp cadsharp - 3 months ago 25
C# Question

How do I convert this LINQ code from C# to VB.NET?

This code simply takes an enum and converts its name to a string. For example, if you pass in

Fruit.Apple
, it will return the string
"Apple"
.

I have passed it through Telerik's converter but it does not translate the LINQ correctly. Any help is appreciated.

internal string ConvertEnumToString<T>(int val) where T : struct, IConvertible
{
string retVal;

try
{
retVal = Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(t => Convert.ToInt32(t), t => t.ToString())[val];
}
catch (Exception)
{
retVal = "UNKNOWN";
}

return retVal;
}

Answer Source

Creating a dictionary of all enum values each time just to get one of them is an overkill. The following code will do what you need with much higher performance:

Function ConvertEnumToString(Of T)(value As Integer) As String
    Dim result As String = DirectCast(DirectCast(value, object), T).ToString()
    Return If(result = value.ToString(), "UNKNOWN", result)
End Function

Code is tested.

Explanation:

1) In .NET it's not allowed to cast integer directly to generic type T, but we can first cast to object and then to any other type.

2) When not defined enum value is converted to string, the result is just a string representation of the corresponding integer value. Thus we use an additional check and replace integer representation with "UNKNOWN".