Orderby() not ordering numbers correctly c#

后端 未结 12 1715
渐次进展
渐次进展 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:44

    Why are you sorting if you only need "the highest version"? It sounds like you could avoid some overhead if you used Max().

    Also, you really should change the column type to integer.

    0 讨论(0)
  • 2020-12-15 03:44
    var items = (from r in results
             select r).OrderBy(q => Convert.ToInt32(q.Version));
    

    Definitely run......

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

    Why are you sorting in a lambda? Why don't you just sort in the query?

    var query = from r in items
                orderby int.Parse( r )
                select r;
    

    Now that we know you are using LINQ to SQL, you might consider making a standard SQL call on this one by doing something like:

    Select ..., Cast( TextWhichShouldBeIntCol As int ) As IntCol
    From ...
    

    Or even

    Select ..., Cast( TextWhichShouldBeIntCol As int ) As IntCol
    From ...
    Order By Cast( TextWhichShouldBeIntCol As int )
    

    That will bleed into your LINQ as an int (and if you use the second iteration, be ordered). That avoids having to go through the resultset twice in LINQ (once for querying, once for ordering).

    0 讨论(0)
  • 2020-12-15 03:45
    var items = (from v in results
                        select v).ToList().OrderBy(x => int.Parse(x.Version));
    
    0 讨论(0)
  • 2020-12-15 03:48

    Int32.Parse is not supported by the LinqToSql translator. Convert.ToInt32 is supported.

    http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx

    http://msdn.microsoft.com/en-us/library/bb882655.aspx

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

    Your problem is somewhere else, the following works:

    new[] { "1", "10", "2", "3", "11" }
        .OrderBy(i => int.Parse(i))
        .ToList()
        .ForEach(Console.WriteLine);
    

    If your problem is LINQ to SQL, then what is happening is CLR is trying to create SQL out of your LINQ and doesn't understand int.Parse. What you can do is first get the data from SQL then order it once all data is loaded:

    var items = (from r in results
                 select r)
                .ToList()
                .OrderBy(q => Int32.Parse(q.Version));
    

    Should do it.

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