Bulli
Bulli

Reputation: 125

Natural Sorting in LINQ

 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?

Upvotes: 0

Views: 732

Answers (2)

Malachi
Malachi

Reputation: 2453

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;

Upvotes: 0

Harald Coppoolse
Harald Coppoolse

Reputation: 30464

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.

Upvotes: 3

Related Questions