Does somebody knows a way to sort enumeration items in code editor, using resharper for example or another VS add-in (i.e. sort the items alphabetically or by integer value) ?
In a project, i've got some huge enumerations with unsorted labels inside, and it will be helpful for readability to sort them.
edit : just to point that since many people mentioned that, i'm perfectly aware of "automatic values" assigned to enum items at compile time if there is no explicit values on them.
Just to get a bit clearer, two examples :
public enum Colors
{
/// <summary>
/// Yellow color
///</summary>
Yellow,
/// <summary>
/// Green color
///</summary>
Green,
/// <summary>
/// Blue color
///</summary>
Blue,
/// <summary>
/// Red color
///</summary>
Red
}
-> we may want to reorder it alphabetically. Admitting integer values are not used since there are not explicitly defined.
Another example :
public enum Colors
{
/// <summary>
/// Yellow color
///</summary>
Yellow = 3,
/// <summary>
/// Green color
///</summary>
Green = 1,
/// <summary>
/// Blue color
///</summary>
Blue = 2,
/// <summary>
/// Red color
///</summary>
Red = 4
}
-> we may like to reorder it by numeric value, or, why not, alphabetically. And so on.
And I also want to keep the comments preceding every entry, which means I can't simply use Excel or a text editor to perform alphabetic sort.
Thank you
To aid with manual sorting, you can use the Resharper functionality for moving members around.
Ctrl-Shift-Alt-Up/Down to move the value at the cursor around within the enum declaration.
This worked for me:
I copied to notepad++, used:
Edit -> Line Operators -> Sort command
Then copied back into VS.
If you are sure their reorder brings no bugs, you can select all of them and paste into an excel worksheet, right click the cells and use the sort
function of EXCEL, then copy them back into VS.
this is an interesting problem, and Id like a solution too, so I wrote a little piece of utility code to do the job
public static string GetReorderedEnumCode<T>()
{
var t = typeof (T);
if (!t.IsEnum)
{
throw new ApplicationException("method requires enum as type parameter");
}
var sb = new StringBuilder();
sb.Append(string.Format(@"public enum {0}
{{
", t.Name));
var names = Enum.GetNames(t);
var vals = (int[])Enum.GetValues(t);
Enumerable.Range(0, vals.Length)
.Select(i => Tuple.Create(names[i], vals[i]))
.OrderBy(t2 => t2.Item1)
.ToList()
.ForEach(r => sb.Append(string.Format(" {0} = {1},",
r.Item1, r.Item2) + Environment.NewLine));
return sb.ToString().TrimEnd(',') + "}";
}
public enum TestEnum
{
FirstValue,
AnotherValue,
LastValue
}
var tmp = Utility.GetReorderedEnumCode<TestEnum>();
Debug.Write(tmp);
Look at your debug output and you'll see your new code - its not ideal but it gives you a solution :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With