意外的Linq OrderBy

时间:2011-08-02 08:07:06

标签: c# linq

我有以下测试失败:

[TestCase]
public void Should_order_numeric_suffix()
{
    var names = new List<string>
                    {
                        "Buisness Unit 7",
                        "Business Unit 1",
                        "Buisness Unit 3",
                        "Business Unit 6",
                        "Business Unit 4",
                        "Buisness Unit 2",
                        "Business Unit 5"
                    };

    List<string> ordered = names.OrderBy(x => x).ToList();

    Assert.That(ordered[0], Is.EqualTo("Business Unit 1"));
}

有序列表的实际顺序是:

Business Unit 2
Business Unit 3
Business Unit 7
Business Unit 1
Business Unit 4
Business Unit 5
Business Unit 6

显然,它按字母顺序正确排序,但我希望也可以订购数字后缀。

3 个答案:

答案 0 :(得分:8)

您的列表中存在拼写错误,有些条目拼写为“商务”而不是“商务”......而“商务”则按字母顺序排在“商务”之前

答案 1 :(得分:1)

您正在寻找自然排序顺序,默认情况下不会在GroupBy中实现 您需要实现自定义IComparer。

当然那些已经存在,例如:

http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting

http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html?showComment=1258020708758#c5034722582649839449

答案 2 :(得分:0)

您可以尝试重写这样的查询:

List<string> ordered = (from n in names
                        orderby n
                        select n).ToList<string>();