我想对一个目录中的字符串数组进行排序,给定一个自定义映射(它实际上是基于它们的扇区对股票名称进行排序)。 我不确定用什么数据结构来表示映射,以及如何编写自定义排序方法。
所以举个例子,假设我有下面的字符串数组:
string[] fileNames = "bac.csv", "c.csv", "cvx.csv", "java.csv", "msft.csv", "xom.csv";这里是映射:
{"bac", "c"} => 0 {"msft", "java"} => 1 {"xom", "cvx"} => 2我想要string [] customSort(string [] fileNames)返回以下内容:
"bac.csv", "c.csv", "java.csv", "msft.csv", "xom.csv", "cvx.csv"您将使用什么数据结构来表示映射,以及编写排序方法的优雅方式是什么?
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"} => 2I 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?
最满意答案
Array.Sort允许你指定一个键的数组,所以你可以做类似...
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);只需修改keys[i] = -1; 语句从给定token变量的映射中获取适当的值。
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.
更多推荐
发布评论