按词典对 C# 进行排序
本文关键字:排序 | 更新日期: 2023-09-27 18:36:50
我有以下代码对字符串进行排序:
class Program
{
static void Main()
{
int x = Convert.ToInt32(Console.ReadLine());
List<string> sampleList = new List<string>();
for (int i=0; i<x; i++)
{
string word = Console.ReadLine();
sampleList.Add(word);
}
foreach (string s in SortByLength(sampleList))
{
Console.Write(s);
}
Console.ReadLine();
}
static IEnumerable<string> SortByLength(IEnumerable<string> e)
{
// Use LINQ to sort the array received and return a copy.
var sorted = from s in e
orderby s.Length descending
select s;
return sorted;
}
}
这段代码按长度对字符串进行排序,我如何按长度和字典顺序进行排序?
例
//Input
4
abba
abacaba
bcd
er
//Output
abacabaabbabcder
在这种情况下工作正常,但是当我有
//Input
5
abba
ebacaba
bcd
er
abacaba
//Output
ebacabaabacabaabbabcder
我的第一个字符串是 ebacaba 这是错误的。
编辑:
默认情况下,non-char 在词法上小于 char,因此,您可以利用这一点并省略ThenBy
但仍会得到相同的结果(功劳归于 Matthew Watson):
string str = "abba ebacaba bcd er abacaba output ebacabaabacabaabbabcder";
string[] strs = str.Split(' ').OrderBy(x => x).ToArray(); //same result, but shorter
源语言:
使用OrderBy
和ThenBy
string str = "abba ebacaba bcd er abacaba output ebacabaabacabaabbabcder";
string[] strs = str.Split(' ').OrderBy(x => x).ThenBy(x => x.Length).ToArray();
您将获得:
abacaba //aba is earlier than abb
abba
bcd
ebacaba
ebacabaabacabaabbabcder
er
你可以使用 :
static IEnumerable<string> SortByLength(IEnumerable<string> e)
{
// Use LINQ to sort the array received and return a copy.
var sorted = e.OrderByDescending(s=>s.Length).ThenBy(r=>r);
return sorted;
}
更改函数 t:
static IEnumerable<string> SortByLength(IEnumerable<string> e)
{
// Use LINQ to sort the array received and return a copy.
var sorted = from s in e
orderby s.Length descending, s
select s;
return sorted;
}
这将输出:
abacabaabbabcder
abacaba
output
abb
bcd
edr
与new List<string>{"abb", "abacaba", "bcd", "edr", "output", "abacabaabbabcder"}
一起使用时
因为它将按 s.Length 排序,然后按 s(词法顺序)排序