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
  • 39,551
  • 56
  • 175
  • 291
splash27
  • 2,057
  • 6
  • 26
  • 49

5 Answers5

3

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,726
  • 5
  • 47
  • 72
2

You need to use ThenBy() using linq

ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.Price).ToList();
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
2

Use Enumerable.ThenBy:

var sortedList = ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.Description).ToList();
w.b
  • 11,026
  • 5
  • 30
  • 49
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.
  • 1,056
  • 7
  • 15
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
  • 30,507
  • 32
  • 137
  • 219