1

For example, I have an object with 3 properties: Name, Price and Description. I need to sort a collection of these objects. It's easy to sort by only one parameter:

var sortedList = ObjectCollection.OrderBy(x => x.Name).ToList();

But how to perform the sorting by 2 parameters (Name and Price). For example, I need to get a list like that:

ItemName1 $100 SomeDescription
ItemName1 $200 AnotherDescription
ItemName1 $250 AnotherDescription
ItemName2 $20 AnotherDescription
ItemName2 $40 Description
ItemName3 $100 Description

and so on. So, the main key is a Name, but if there are several items with the same name then the second key is the price. How to do this?

Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
splash27
  • 1,807
  • 4
  • 21
  • 45

5 Answers5

2

Use the ThenBy extension, as it does not override previously used OrderBy calls.

var sortedList = ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.Price).ToList();
Marcel N.
  • 13,120
  • 5
  • 43
  • 68
2

You need to use ThenBy() using linq

ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.Price).ToList();
Sajeetharan
  • 186,121
  • 54
  • 283
  • 331
2

Use Enumerable.ThenBy:

var sortedList = ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.Description).ToList();
w.b
  • 10,250
  • 5
  • 25
  • 44
1
var sortedList = ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.SecondPropertyToOrderBy).ToList();

You can chain the OrderBy or OrderByDescending like this. I Hope this helps

S.L.
  • 986
  • 6
  • 14
1

You can use Linq:

ObjectCollection.OrderBy(x => x.Name).
                 ThenBy(x => x.Price).ToList();

If you can't use Linq, you can write a custom comparator.

Daniel Peñalba
  • 27,557
  • 31
  • 124
  • 209