-2

I have a list of objectsList<Batch> batchesList new List<Batch>();with fields string orderNo and int lineNo

I print "orderNo-lineNo"

I want to sort it by orderNo then lineNo. The problem I have is that using linq's sort(), this will sort as a string, thus 11AG131-13 would actually come before 11AG131-2

batchesList.Sort((x, y) => (x.orderNo + x.lineNo).CompareTo(y.orderNo + y.lineNo));

Thanks for help

Sam Hajari
  • 354
  • 4
  • 10
  • 1
    If you want them to be sorted as int's you have to convert them to `int` before sorting. – maccettura Aug 11 '17 at 14:50
  • I'm in a car writing in a mobile... Try OrderBy(int.tryparse(your string))The by(int.TryParse(secondstring)) – Juan Aug 11 '17 at 14:52
  • Just so I am clear.. you want `11AG131-2` to come before `11AG131-13` even though `11AG131-13` could have a `lineNo` that is less than `11AG131-2`'s `lineNo`? – Grizzly Aug 11 '17 at 15:00
  • @T_Roy `2` is the `lineNo` and `11AG131` is the `orderNo`. – juharr Aug 11 '17 at 15:06
  • @juharr ohhhhh I see now.. I was interpreting that all to just be the `orderNo`.. okay I see now. Sorry about my confusion – Grizzly Aug 11 '17 at 15:07
  • There is the separate issue of ordering the `orderNo` But that's only an issue if it's length can vary like "2AG131" and "11AG131" – juharr Aug 11 '17 at 15:08

3 Answers3

6
var sortedBatches = batchesList.OrderBy(b => b.orderNo)
                               .ThenBy(b => b.lineNo)
                               .ToList();
Maxim
  • 1,995
  • 1
  • 19
  • 24
1
var newList = (from x in batchesList orderby x.orderNo, x.lineNo select x).ToList();
J. D.
  • 1,351
  • 8
  • 13
0

There's an idiomatic approach to ordering on multiple values:

batchesList.Sort((x, y) => {
    var i = x.orderNo.CompareTo(y.orderNo);

    if (i != 0) { return i; }

    return x.lineNo.CompareTo(y.lineNo);
});
cdhowie
  • 158,093
  • 24
  • 286
  • 300