0
 SortedList = List.OrderBy(object1=> object1.Order.Split(';')[0])
                        .ThenBy(object2=> object2.Order.Split(';')[1])
                        .ThenBy(object3=> object3.Order.Split(';')[2])
                        .ToList();

Order has a Value off 1;1;1. I Split at ";" and sort the Elements. But i get a "alphabetical Order". That means 1,10,2,3. String Format to 4 Digits is not possible because the object is not a String. Is a natural Order possible in LINQ?

Bulli
  • 115
  • 1
  • 8

2 Answers2

3

Are you certain that every Object.Order is a colon separated string of at least 3 integer values?

Why not convert these three values to integer and sort by the parsed values?

var result = myInputSequence.Select(sourceItem => new
{

    SplitOrderNumbers = (sourceItem.Order.Split(';')
        .Select(splitItem => Int32.Parse(splitItem))
        .Take(3)
        .ToList(),
    OriginalSourceItem = sourceItem,
})
.OrderBy(item => item.SplitOrderNumbers[0])
.ThenBy(item => item.SplitOrderNumbers[1])
.ThenBy(item => item.SplitOrderNumbers[2])
.Select(item => item.OriginalSourceItem);

Bonus point: unlike in your solution, you split your orders only once.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • 1
    I was about to post this minus the single split. I humbly retract and upvote for your better answer. – Broom Nov 06 '18 at 14:13
  • Technically speaking I think the underlying quicksort algorithm is gonna re-issue those split operations – Malachi Nov 06 '18 at 14:39
0

You can customize ordering behavior to your needs by implementing IComparer. See: Microsoft Documentation. That said, I like Harald Coppoolse's answer better. In fact, I like his answer so much I like it in linq syntax too:

var result = from n in myInputSequence
                let split = n.Order.Split(';').
                    Select(splitItem => Int32.Parse(splitItem)).
                    Take(3).ToList()
                orderby split[0], split[1], split[2]
                select n;
Malachi
  • 2,260
  • 3
  • 27
  • 40