1

I have a list of data that looks like so:

enter image description here

What I want to do is use LINQ to order by option code, then by any box sizes that start with 'W', then order by the rest of the box sizes. The ordered list should look order exactly how it is shown above.

What I have Tried 1:

var check = _routeManagementService.GetAllOptionsWithBoxSizes().Select(x => new OptionDataViewModel
{
      Id = x.Id,
      BoxSizeId = x.BoxSizeId,
      Name = x.Name,
      OptionCode = x.OptionCode,
      BoxSize = x.BoxSize,
      Time = x.Time
 }).OrderBy(x => x.OptionCode).ThenBy(x => x.BoxSize).ToList();

What I have Tried 2:

var check = _routeManagementService.GetAllOptionsWithBoxSizes().Select(x => new OptionDataViewModel
{
     Id = x.Id,
     BoxSizeId = x.BoxSizeId,
     Name = x.Name,
     OptionCode = x.OptionCode,
     BoxSize = x.BoxSize,
     Time = x.Time
}).OrderBy(x => x.OptionCode)
  .ThenBy(x => x.BoxSize.StartsWith("W"))
  .ThenBy(x => x.BoxSize).ToList();

In Either case the initial option code sort would work but then it would still show box sizes containing F first before ones containing W. How can I write this linq query to correctly sort the list in the way I want?

Thank you for any suggestions or comments!

Selthien
  • 1,178
  • 9
  • 33
  • Have you tried ThenByDescending method? – Ivan-San Sep 11 '19 at 21:35
  • 3
    `.ThenBy(x => !x.BoxSize.StartsWith("W"))` (or @Ivan-San's solution) `false` sorts **before** `true`. – mjwills Sep 11 '19 at 21:37
  • @mjwills That worked! That is strange that it works that way. Reading it it looks like your trying to sort by items that don't start with W? – Selthien Sep 11 '19 at 21:42
  • 1
    You need to think of the return type of the expression. It is boolean. Now ask yourself - how are booleans sorted? Answer - `false` then `true`. – mjwills Sep 11 '19 at 21:43
  • Hm. Makes sense when you say it that way. Thank you! – Selthien Sep 11 '19 at 21:43
  • Possible duplicate of [Linq order by boolean](https://stackoverflow.com/questions/5408177/linq-order-by-boolean) – Sach Sep 11 '19 at 21:55

0 Answers0