C#:自定义数组排序 [英] C#: custom array sorting

查看:117
本文介绍了C#:自定义数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定自定义映射的情况下,我想对目录中的字符串数组进行排序(实际上是根据其行业对股票名称进行排序).我不确定用于表示映射的数据结构以及如何编写自定义排序方法.

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";

这是映射:

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

我希望string [] customSort(string [] fileNames)返回以下内容:

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

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

您将使用什么数据结构来表示映射,以及编写sort方法的一种优雅方法是什么?

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

推荐答案

Array.Sort允许您指定键的数组,因此您可以执行以下操作...

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);

只需修改keys[i] = -1;语句,即可在给定token变量的情况下从映射中获取正确的值.

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

这篇关于C#:自定义数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆