我有一个用于排序字符串的代码:
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()
- Teodor Kurtev