String "Sort Template" in C #

I am trying to find an easy way to sort a rowset based on a "sorting pattern". I'm sorry if my wording is confusing, but I can't think of a better way to describe it (maybe someone can come up with a better way to describe it after reading what I'm trying to do?).

Consider the following list of strings (my "sorting pattern", each item in the "command" list):

  • [FA, TY, AK, PO, PR, ZZ, QW, BC]

I would like to use the order of the lines in this list to sort the list of these commands. For example, I need the following list:

  • [TY, PR, PR, ZZ, BC, AK]

to sort in the following list based on the "sort template":

  • [TY, AK, PR, PR, ZZ, BC]

What would be a good way to do this? The best idea I have is to use an enumeration ...

enum Command { FA, TY, AK, PO, PR, ZZ, QW, BC }; 

... and do Enum.Parse () for each command in my list, I want to sort this list from the list of lines in the list of commands, which will then be sorted according to the order of listing.

I dont know. The listing seems to work, but is there a better way I could do this?

+4
source share
4 answers

You can use Dictionary<string, int> to store and retrieve the sort pattern markers. However, this basically does the same thing as your enum (only, perhaps in a slightly more readable way), because Enum.Parse can be confusing here.

 var ordering = Dictionary<string, int>(); ordering.Add("FA", 0); ordering.Add("TY", 1); // â€Ļ MyList.Sort((a, b) => ordering[a].CompareTo(ordering[b])); 

This uses the appropriate overload of the List<T>.Sort to compare two elements based on their value in the template dictionary.

+2
source

Here is a very easy way to do it!

 List<string> template = new List<string>{ "ZD", "AB", "GR"}; List<string> myList = new List<string>{"AB", "GR", "ZD", "AB", "AB"}; myList.Sort((a, b) => template.IndexOf(a).CompareTo(template.IndexOf(b))); 
+3
source

You can rename your commands, for example

 [1FA, 2TY, 3AK, 4PO, 5PR, 6ZZ, 7QW, 8BC] 

and cross out the first character when you were ready to use it. I think this is called kludge .

I can't help but think that you can get mileage by using a SortedList , but in reality it will work more or less like your enum

 SortedList Commands = new SortedList(); Commands.Add(1,FA); Commands.Add(2,TY); //etc 
+1
source

Use the command template (I think it called)

write a sorting method that sorts the list, but uses an external method to compare between pairs of objects ... Then pass the delegate to it the comparison method ... Write a comparison method to take two members of the list and the sorting template as input parameters ... In the method return -1, a, or + 1 depending on whether the first member of the pair or the second element in the list of templates is found.
In your sorting method, use the return value of the comparison method to implement sorting, regardless of what kind you are doing ...

+1
source

All Articles