0

I have a List of Objects (RunSummary) sorted by a UniqueId column, then RunNo column. But UniquId objects are of type String. I want to sort by UniqueId as Integer objects (not as 1,10,11,3 but 1,3,10,11). Here is my code:

public List<RunSummary> GetRunSummariesForUniqueIds(List<String> uniqueIds)
{
    using (var context = new ELSORegistryEntities())
    {
        context.Configuration.ProxyCreationEnabled = false;

        List<RunSummary> runSummaries = context.RunSummaries
            .Where(param => uniqueIds.Contains(param.UniqueId))
            .OrderBy(param => param.UniqueId)
            .ThenBy(param => param.RunNo)
            .ToList<RunSummary>);              

        return runSummaries;
    }
}        

I have tried with

List<RunSummary> runSummaries = context.RunSummaries
    .Where(param => uniqueIds.Contains(param.UniqueId))
    .OrderBy(param => Convert.ToInt32(param.UniqueId))
    .ThenBy(param => param.RunNo)
    .ToList<RunSummary>();

but it doesn't work. How do I sort in LINQ?

Draken
  • 3,134
  • 13
  • 34
  • 54
alenan2013
  • 207
  • 3
  • 22
  • 2
    What specifically isn't working? Are you getting an exception? Or if you get incorrect results what are they? – juharr Jun 20 '16 at 16:43
  • 2
    @juharr I didn't think you could use a function like `int.Parse(param.UniqueId)` inside a `DBContext` query? – Peter Smith Jun 20 '16 at 16:44
  • i guess, that you can't use Convert.ToInt32 in LINQ query to DB, but give us an answer what's wrong.. – Marek Woźniak Jun 20 '16 at 16:45
  • Possibly related http://stackoverflow.com/questions/16694716/entity-framework-linq-expression-converting-from-string-to-int – juharr Jun 20 '16 at 16:47
  • You could do ToList before sorting, and use the int parsing logic after that ... – Sam.C Jun 20 '16 at 16:48
  • @Sam.C Better yet to use `AsEnumerable`. – juharr Jun 20 '16 at 16:49
  • I got an exception :" LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression." – alenan2013 Jun 20 '16 at 16:56
  • 1
    I can't agree with the closure of this topic. The given answer on the "selected" post is not the correct answer. It works but it isn't correct. – Leandro Soares Jun 20 '16 at 16:57
  • Why are the `UniqueId` values stores as strings? If they're really integers, then they should have a different data type in your schema. – StriplingWarrior Jun 20 '16 at 17:04

1 Answers1

2

you can't use Convert.ToInt32 inside the query, you should order after the query

List<RunSummary> runSummaries = context.RunSummaries.Where(param => uniqueIds.
Contains(param.UniqueId)).ToList<RunSummary>()
.OrderBy(param => Convert.ToInt32(param.UniqueId))
.ThenBy(param => param.RunNo).ToList();
Boo
  • 663
  • 5
  • 10