C
C#2y ago
Dultus

❔ Can I generalise this method?

public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums)
{
string[] values = value.Split(',');
for (int i = 0; i < enums.Length; i++)
{
var type = enums[i];
yield return (Enum)Converter.GetEnumFromValue<type>(values[i]);
}
}
public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums)
{
string[] values = value.Split(',');
for (int i = 0; i < enums.Length; i++)
{
var type = enums[i];
yield return (Enum)Converter.GetEnumFromValue<type>(values[i]);
}
}
Lets say I pass in "0,3,2" - I also want to pass in the Types of the Enusm I want to get them converted as. For example I split them into three different Enums, 0 being the category, 3 the subcategory and 2 a list item. Any way to generalise this?
4 Replies
Anton
Anton2y ago
that enum method should have a non-generic overload which takes the type as one of the arguments if not, you can resolve the generic with reflection, but that's generally bad
TheRanger
TheRanger2y ago
this worked for me
public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums)
{
string[] values = value.Split(',');
for (int i = 0; i < enums.Length; i++)
{
var type = enums[i];
var index = int.Parse(values[i]);
yield return (Enum)Enum.GetValues(type).GetValue(index);
}
}
public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums)
{
string[] values = value.Split(',');
for (int i = 0; i < enums.Length; i++)
{
var type = enums[i];
var index = int.Parse(values[i]);
yield return (Enum)Enum.GetValues(type).GetValue(index);
}
}
Dultus
DultusOP2y ago
Yeah, built it somewhat like that. Thanks!
public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums)
{
string[] values = value.Split(',');
if (values.Length != enums.Length)
{
throw new MismatchedEnumLengthsException();
}
for (int i = 0; i < enums.Length; i++)
{
yield return (Enum)Enum.Parse(enums[i], value);
}
}
public static IEnumerable<Enum> TransformIdToEnums(string value, params Type[] enums)
{
string[] values = value.Split(',');
if (values.Length != enums.Length)
{
throw new MismatchedEnumLengthsException();
}
for (int i = 0; i < enums.Length; i++)
{
yield return (Enum)Enum.Parse(enums[i], value);
}
}
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?