David Hodgson
David Hodgson

Reputation: 10344

C#: custom array sorting

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?

Upvotes: 1

Views: 2238

Answers (2)

Adam Robinson
Adam Robinson

Reputation: 185613

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.

Upvotes: 7

Promit
Promit

Reputation: 3507

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?

Upvotes: 1

Related Questions