15

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

6
  • Do you mean via Intellisense or are you "printing" them to screen or a control? Or are you talking about actually resorting the actual items in the enumeration automatically? Aug 12, 2011 at 10:05
  • 7
    I hope the Enums each specify a value explicitly, otherwise their values will change if you reorder them
    – Dean Chalk
    Aug 12, 2011 at 10:07
  • I hope the Enums each do NOT rely on a specific value, otherwise their values will change if you reorder them. :)
    – leppie
    Aug 12, 2011 at 11:02
  • As i specified in the question, we may admit that there IS an explicit value for each item, so reordering them won't affect program's behaviour.
    – AFract
    Aug 12, 2011 at 12:06
  • And on the other hand, of course if there is no numeric value but only a label, only alphabetical sort may have a sense.
    – AFract
    Aug 12, 2011 at 12:07

6 Answers 6

5
  1. Select and cut the enum values.
  2. Paste them into Vim.
  3. :sort.
  4. Cut and paste them back.

(It's useful to get into the habit of adding a trailing comma to the last enum value, even though it's not required, as it makes reordering and adding items easier.)

As @Dean Chalk pointed out, reordering the items in a enum will affect the underlying number of that item unless you use explicit numbering. It will only affect you if you are storing these numbers (e.g. to a database), using them to communicate with external processes or casting your enum to another enum.

2
  • As i answered to Danny Chen, this method won't work if enum items contains summaries.
    – AFract
    Aug 12, 2011 at 12:08
  • @Richard: in which case see my new answer for easier manual sorting.
    – Paul Ruane
    Aug 12, 2011 at 13:16
5

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.

1
  • Not yet a full automated solution, but nice shortcut. Thanks.
    – AFract
    Aug 12, 2011 at 13:34
4

This worked for me:

I copied to notepad++, used:

Edit -> Line Operators -> Sort command

Then copied back into VS.

1
  • Sorry but your answer completely ignores the comment before each enum entry. And also the concern about sorting them by numeric value instead of labels. There are a lot of easy ways to sort text by alphabetic order, if answer was so obvious I wouldn't have posted my question on SO, this was clearly explained at the end of the question...
    – AFract
    Aug 16, 2017 at 10:08
2

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.

1
  • Thank you but it won't work if the enum's items are preceded by /// <summary> comments, and it won't work to sort them by numerical value.
    – AFract
    Aug 12, 2011 at 12:04
2

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 :)

1
  • 1
    Funny piece of code. But, since it runs on compiled code, it won't keep summaries ;). And also, requires .Net 4 (for Tuple). I was searching for a solution running directly into VS, like a refactoring tool. I did'nt find anything in Refactor! or resharper or any other add-in. But thank you for the time spent to write this one.
    – AFract
    Aug 12, 2011 at 12:19
-1

I haven't found a good way in the editor (Visual Studio or ReSharper), but it is really easy to copy and paste a generic comma separated list into a site like this and have it sort them.

1
  • Like I said previously to Danny Chen, this WON'T work since it will lose comments, and doesn't work neither for sorting on numeric value of entries. I've edited the original question about this.
    – AFract
    Oct 25, 2013 at 8:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.