browsermator
browsermator

Reputation: 1353

Linq query to sort strings like numbers in ASP.NET-Core 3.0 and above

I've recently upgraded from ASP.NET-Core 2.2 to ASP.NET-Core 3.1. I have quantities that are strings (most are just numbers but we have some that are 100 Feet, 1 Spool, etc...) In 2.2 I could sort these by using PadLeft, but this throws an error in ASP.NET-Core3.0 and above. Does anyone know a good workaround for using LINQ queries which sort numbers that are strings? (so you don't get "999", then "99", then "888", "88", etc...)

My old solution was:

  IQueryable<InventoryItem> Items;
  Items = from m in _context.Inventory.Where(m => m.Removed == 0)
                                              select m;
    case "Quantity":
         Items = Items.OrderByDescending(s => s.Quantity.PadLeft(maxlen, '0'));
         break;

This no longer works because ASP.NET-Core 3.1 evaluates it at the server instead of at client. It doesn't understand .PadLeft()

Added: I am paginating, so the query is running on this line:

 items = await source.Skip(
                    (pageIndex - 1) * pageSize)
                    .Take(pageSize).ToListAsync();

If I go toList before then, I'm not limiting the results from the query to the number of results chosen...

Upvotes: 1

Views: 776

Answers (2)

Den
Den

Reputation: 786

Try to do this. Convert.ToInt32 is automatically converted from EF into a query.

Items = Items.OrderByDescending(s => Conert.ToInt32(s.Quantity));

Upvotes: 0

Serge
Serge

Reputation: 43931

You have an error because Linq can't convert your code to Sql query. So you have to download data from db at first using ToList (or ToArray) for example. After this you can use any kind of algorithm to sort the list.

Items = _context.Inventory.Where(m => m.Removed == 0).ToList();

Items = items.OrderByDescending(s => s.Quantity.PadLeft(maxlen,'0'));

Upvotes: 2

Related Questions