简体   繁体   English

Linq 忽略 OrderBy 中的空格

[英]Linq ignoring spaces in OrderBy

I am running a query to retrieve a list of suburbs.我正在运行查询以检索郊区列表。 When I apply an OrderBy (I want the ordered alphabetically)当我应用 OrderBy 时(我想要按字母顺序排列)

query.OrderBy(s => s.Name);

I am given the following order:我得到以下命令:

MOUNT ADA
MOUNTAIN BAY
MOUNTAIN GATE
MOUNTAIN VIEW
MOUNT ALFRED
MOUNT BEAUTY

It appears that the spaces are ignored and ordering by the suburb name without spaces.似乎空格被忽略并按郊区名称排序,没有空格。 What do I need to do to order by correctly?我需要做什么才能正确订购? I think they should be in the following order:我认为它们应该按以下顺序排列:

MOUNT ADA
MOUNT ALFRED
MOUNT BEAUTY
MOUNTAIN BAY
MOUNTAIN GATE
MOUNTAIN VIEW

It appears that your database setting are having an affect on the sorting order due to the spaces between the individual character groupings.由于各个字符组之间的空格,您的数据库设置似乎对排序顺序有影响。 If you where to replace those spaces using the string method Replace() the result set might get the needed results.如果您使用字符串方法Replace()替换这些空格,结果集可能会获得所需的结果。 But, without having a PostgreSQL 12.1 Database with your specific setting it is impossible to know whether this will generate the desired results.但是,如果没有具有特定设置的 PostgreSQL 12.1 数据库,就不可能知道这是否会产生所需的结果。

    private static void TestOrderList()
    {
        var list = new List<string>();
        list.Add("MOUNTAIN GATE");
        list.Add("MOUNT ADA");
        list.Add("MOUNTXADA");
        list.Add("MOUNTAIN BAY APP TOAST");
        list.Add("MOUNTAIN BAY APP ATOAST");
        list.Add("MOUNTAIN BAY APPA");
        list.Add("MOUNTAIN BAY");
        list.Add("MOUNT ALFRED");
        list.Add("MOUNTAIN VIEW");
        list.Add("MOUNT BEAUTY");

        var q = list.AsEnumerable().OrderBy(r => r.Replace("~", ""));
        q.ToList().ForEach(s => Console.WriteLine(s));
    }

Disclaimer : This is not so much a solution, but more like a test case.免责声明:这与其说是解决方案,不如说是一个测试用例。 I choose a Tilda since it is low on the sorting order of ASCII characters.我选择了 Tilda,因为它对 ASCII 字符的排序顺序很低。

I have not changed any logic, but a simple iteration gave me the expected results.我没有改变任何逻辑,但是一个简单的迭代给了我预期的结果。

public class LinqOrderingForWords
{
    IList<string> _places;

    public LinqOrderingForWords()
    {
        _places = new List<string> { "MOUNT ADA", "MOUNTAIN BAY", "MOUNT BEAUTY", "MOUNTAIN VIEW", "MOUNTAIN GATE", "MOUNT ALFRED", "MOUNT ADA ONE" };
    }

    public void OrderPlaces()
    {
        var sorted = _places.OrderBy(s => s);
        sorted.ToList().ForEach(s => Console.WriteLine(s));
    }
}

See the dotnet fiddle here .请参阅此处的 dotnet fiddle

Is this what you desire to see?这是你想看到的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM