proggrock
proggrock

Reputation: 3289

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?

Upvotes: 3

Views: 1717

Answers (3)

configurator
configurator

Reputation: 41620

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;

Upvotes: 3

Jodrell
Jodrell

Reputation: 35696

how about?

var orderedFilenames = filenames.OrderBy(
    f => (int)Enum.Parse(typeof(ProcessWorkFlowOrder), f));

However, I'm not sure that maintaining this enum is the best approach, better to write a function to define the order algorithm, what if enum does not contain the file name.

EDIT with TryParse

var orderedFilenames = filenames.OrderBy(f => {
       ProcessWorkFlowOrder parsed;
       int result = 0;
       if (Enum.TryParse<ProcessWorkFlowOrder>(f, out parsed))
           result = (int)parsed;
       return result;
    });

What rules would you use to construct the enum or an order preserving list or, is the order purely arbitary?

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126804

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.

Upvotes: 5

Related Questions