1

I would like to sort an array of strings in a directory, given a custom mapping (it's actually a sorting of stock names based on their sector). I am unsure of what data structures to use to represent the mapping, and how to write the custom sort method.

So for instance, suppose I had the following string array:

string[] fileNames = "bac.csv", "c.csv", "cvx.csv", "java.csv", "msft.csv", "xom.csv";

And here are the mappings:

{"bac", "c"} => 0
{"msft", "java"} => 1
{"xom", "cvx"} => 2

I would like string[] customSort(string[] fileNames) to return the following:

"bac.csv", "c.csv", "java.csv", "msft.csv", "xom.csv", "cvx.csv"

What data structure would you use to represent the mappings, and what's an elegant way of writing the sort method?

2 Answers 2

7

Array.Sort allows you to specify an array of keys, so you can do something like...

int[] keys = new int[fileNames.Length];

Dictionary<string, int> mapping = new Dictionary<string, int>(StringComparer.CurrentCultureIngoreCase);

// set up our mappings like so
mapping.Add("bac", 0);
mapping.Add("c", 0);
mapping.Add("msft", 1);
mapping.Add("java", 1);
mapping.Add("xom", 2);
mapping.Add("cvx", 2);
// etc

for(int i=0; i < keys.Length; i++)
{
    string token = System.IO.Path. GetFileNameWithoutExtension(fileNames[i]);

    int mappingKey;

    if(!mapping.TryGetValue(token, out mappingKey)) mappingKey = int.MaxValue;

    keys[i] = mappingKey; 
}

Array.Sort<int, string>(keys, fileNames);

Just modify the keys[i] = -1; statement to get the proper value from your mappings given the token variable.

Sign up to request clarification or add additional context in comments.

3 Comments

That would require me to write: key["bac"] = 0; key["c"]=0; key["msft"]=1; key["java"]=1; etc. right? Is there a more concise way of writing this?
No, you wouldn't be writing this. I'll edit the code to be clearer and perhaps make it more concise.
Maybe I'm doing something wrong, but this didn't sort the array as it should. See my answer below.
1

Um...it seems like if you have your mapping in a usable format, you could just write up a custom IComparer implementation and hand it to Array.Sort. Maybe I'm missing some important detail in your question?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.