Ordering <String> List by Matching Enum Name

I don’t know how to do it. I need to display the list of files in a different order than they are presented on our file server.

I thought one way would be to arrange the list of strings using a consistent value for the name enum.

Let's say I have a complete list of lines:

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

And I have a related listing to show files in a specific order:

    public enum ProcessWorkFlowOrder 
    {    
       File1,
       File3,
       File2           
    }

The string value "filenames" in the list will exactly match the name Enum.

What is the best way to match and arrange a list of file names by their matching enumeration value?

+3
source share
3 answers

, , , .

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

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

Join .

+5

, , , :

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;
+3

What about?

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

However, I'm not sure that saving this enumeration is the best approach, it is better to write a function to determine the ordering algorithm, which if the enumeration does not contain a 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 create an enumeration or order list, or is the order purely pure?

+1
source

All Articles