在C#中的字符串数组的自定义排序 [英] Custom sorting of a string array in C#

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

问题描述

我传递给我的程序在C#中的字符串数组或数组列表。这里是一个什么样的字符串包含一些例子:

I have a string array or arraylist that is passed to my program in C#. Here is some examples of what those strings contain:

SPR 2009
2006年总和
2010年秋季
2007年秋季刊

"Spr 2009" "Sum 2006" "Fall 2010" "Fall 2007"

我希望能够进行排序在今年这个数组,然后在赛季。有没有写一个排序函数来告诉它在今年随后的赛季进行排序的方法。我知道,如果他们是分开的,但我不能帮什么是被赋予对我来说会更容易些。

I want to be able to sort this array by the year and then the season. Is there a way to write a sorting function to tell it to sort by the year then the season. I know it would be easier if they were separate but I can't help what is being given to me.

推荐答案

您需要编写将在适当的方式任意两个字符串比较的方法,然后你可以将其转换方法为一个比较<串GT; 委托传递到的Array.Sort

You need to write a method which will compare any two strings in the appropriate way, and then you can just convert that method into a Comparison<string> delegate to pass into Array.Sort:

public static int CompareStrings(string s1, string s2)
{
    // TODO: Comparison logic :)
}
...

string[] strings = { ... };
Array.Sort(strings, CompareStrings);

您可以做同样的事情用一个通用的清单,也:

You can do the same thing with a generic list, too:

List<string> strings = ...;
strings.Sort(CompareStrings);

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

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