【发布时间】:2016-03-01 15:47:40
【问题描述】:
我有这个用于排序字符串的代码:
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,这是错误的。
【问题讨论】:
-
你可以试试:
var sorted = e.OrderByDescending(x => x.Length).ThenBy(x => x).ToList() -
我不明白您想要为第二种情况(5 个输入)实现的模式,介意给出预期的输出吗?
标签: c# sorting lexicographic