按字典顺序排序C#

时间:2016-03-01 15:47:40

标签: c# sorting lexicographic

我有这个用于排序字符串的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdownmainmenu">
  <div class="hedmainmenu">
    <a href="#">
      <i class="fa fa-newspaper-o"></i> News <span class="showarrowmainmenu arrowright"></span>
    </a>
  </div>
  <ul class="showmenu">
    <li><a href="add_news.php">Add news</a>
    </li>
    <li><a href="news.php">All News</a>
    </li>
  </ul>
</div>

此代码按长度排序字符串,如何按长度和字典顺序进行排序?

示例

 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

我的第一个字符串是ebacaba,这是错误的。

3 个答案:

答案 0 :(得分:2)

修改

默认情况下,非char在词法上小于char,因此,您可以利用它并省略ThenBy但仍会得到相同的结果(Credit转到Matthew Watson):

string str = "abba ebacaba bcd er abacaba output ebacabaabacabaabbabcder";
string[] strs = str.Split(' ').OrderBy(x => x).ToArray(); //same result, but shorter

<强>原始

使用OrderByThenBy

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

答案 1 :(得分:2)

你可以使用thenby:

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

答案 2 :(得分:0)

更改你的功能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(词汇顺序)

排序