0

How can I sort an array using a predefined sorted array?

I'm working with a web API that you can query for a list of information, which you can specify the things you need in the list. The data list gets returned separated by newlines.

The problem is that the API returns the information in a specific order, regardless of what order you specify yourself.

For example,

Query("second,third,first,fourth");
// returns string:
@"Info for first
Info for second
Info for third
Info for fourth"

I then have to parse it into a dictionary: { "first", "Info first" }, {"second", "Info second"}, etc I could just base it off the parameter list I used, however unless you memorize the correct order for all data, it's a bit annoying.

So, how could I sort it using a predefined sorted list. Such as:

// All possible queries sorted correctly
{ "first", "second", "third", "fourth", "fifth", etc } 
// My unsorted list
{ "third", "first", "fifth"}
// Would become:
{ "first", "third", "fifth"}

(These are placeholder values to make it more clear)

4
  • How does the order matter when adding to a dictionary? Commented Jul 21, 2019 at 1:44
  • SortedDictionary<TKey,TValue>, if it's actually needed. Do you have means to match/map the query criteria with the response content? If you do, you probably don't need any sorting. If you don't, you have a bigger problem you need to fix first. Commented Jul 21, 2019 at 2:09
  • @stickybit Sorry if I'm bad at explaining. I need to sort so that the dictionary keys are assigned their correct value. I split the data by newlines and put them in a dictionary with their corresponding name (key). If I don't sort my query list to the correct order the key names can be incorrect. I'll check the provided answers in an hour Commented Jul 21, 2019 at 3:05
  • Ended up using Fastest way to get list in custom order, as it seems to be a bit faster. Commented Jul 22, 2019 at 0:36

1 Answer 1

0

You can sort them using a method to compare these results to determine which one comes earlier according to your list

private bool IsBefore(string A, string B)
{
    int iA, iB;
    iA = Array.IndexOf(RefArray, A);
    iB = Array.IndexOf(RefArray, B);
    if (A < B)
        return true;
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.