Orderby() not ordering numbers correctly c#

后端 未结 12 1714
渐次进展
渐次进展 2020-12-15 03:08

I am writing an app for my company and am currently working on the search functionality. When a user searches for an item, I want to display the highest version (which is st

相关标签:
12条回答
  • 2020-12-15 03:23

    try this:

    var items = results.(Select(v => v).OrderBy(v => v.PadLeft(4));
    

    that'll work in Linq2Sql

    0 讨论(0)
  • 2020-12-15 03:24

    It sounds like you have a text value instead of a numeric value.

    If you need to sort, you can try:

    var items = (from r in results
                 select r);
    return items.OrderBy( v=> Int.Parse(v.Version) );
    
    0 讨论(0)
  • 2020-12-15 03:29

    There's an awesome piece of code that does a great job when it comes to natural sorting. Its name is AlphanumComparator.

    Sample code:

    var ordered = Database.Cars.ToList().OrderBy(c => c.ModelString, new AlphanumComparator());
    

    Note that the list must be in memory.

    If you get the C# version, do this:

    AlphanumComparator : IComparer<string>
    

    and

    public int Compare(string x, string y)
    
    0 讨论(0)
  • 2020-12-15 03:30
    var query = from r in items
                let n = int.Parse(r)
                orderby n
                select n;
    
    0 讨论(0)
  • 2020-12-15 03:37

    If you're unable to change your table definition (so the version is a numeric type), and your query really is as listed (your not using skip, or take, or otherwise reducing the number of results), the best you can do is call "ToList" on the unsorted results, which when you then apply an OrderBY lambda to it will take place in your code, rather than trying to do it at the SQL Server end (and which should now work).

    0 讨论(0)
  • 2020-12-15 03:42

    I made a test. I have the following code.

    string[] versions = { "1", "2", "10", "12", "22", "30" };
    foreach (var ver in versions.OrderBy(v => v))
    {
         Console.WriteLine(ver);
    }
    

    As expected the result is 1, 10, 12, 2, 22, 30 Then lets change versions.OrderBy(v => v)) to versions.OrderBy(v => int.Parse(v))). And it works fine: 1, 2, 10, 12, 22, 30

    I think your problem is that you have nondigit chars in your string like '.'. What kind of exception do you get?

    0 讨论(0)
提交回复
热议问题