Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering a List<String> by matched Enum's name value

A little unsure of how to do this. I need to display a list of files in a different order than they are presented on our file server.

I was thinking one way would be to order a list of strings by a matched enum's name value.

Let's say I have a full list of strings:

    List<string> filenames = new List<string>();

And I have a related enum to show the files in a certain order:

    public enum ProcessWorkFlowOrder 
    {    
       File1,
       File3,
       File2           
    }

The "filenames" string value in the List will match exactly the Enum's name.

What is the best way to match and order the FileNames list by its matched enum value?

like image 393
proggrock Avatar asked Dec 09 '25 20:12

proggrock


2 Answers

If the filenames match exactly, I wouldn't use an enum but rather another order-preserving list.

List<string> namesInOrder = ...
List<string> files = ...

var orderedFiles = from name in namesInOrder
                   join file in files 
                   on name equals file
                   select file;

Join preserves the order of the first sequence and will therefore allow you to use it to order the second.

like image 182
Anthony Pegram Avatar answered Dec 11 '25 08:12

Anthony Pegram


If you already have the enum and you can't change it to a list of string like Anthony suggests, you can use this:

var order = Enum.GetValues(typeof(ProcessWorkFlowOrder))
                .OfType<ProcessWorkFlowOrder>()
                .Select(x => new {
                                   name = x.ToString(),
                                   value = (int)x
                        });

var orderedFiles = from o in order
                   join f in filenames
                   on o.name equals f
                   orderby o.value
                   select f;
like image 33
configurator Avatar answered Dec 11 '25 08:12

configurator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!