简体   繁体   English

C#:自定义数组排序

[英]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: 我希望string [] customSort(string [] fileNames)返回以下内容:

"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? 您将使用什么数据结构来表示映射,以及编写sort方法的一种优雅方法是什么?

Array.Sort allows you to specify an array of keys, so you can do something like... 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);

Just modify the keys[i] = -1; 只需修改keys[i] = -1; statement to get the proper value from your mappings given the token variable. 给定token变量的语句从映射中获取适当的值。

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 . 嗯...好像您的映射格式可用,您可以编写一个自定义IComparer实现并将其交给Array.Sort Maybe I'm missing some important detail in your question? 也许我在您的问题中缺少一些重要的细节?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM