Sort C # list using 2 fields

I have a list of my custom objects. The object contains 1 line and 2 decimal places. I would like to sort the list based on the 2nd decimal field, then descending to the first decimal field.

For instance,

object 1 -> "a", 100, 10 object 2 -> "b", 300, 0 object 3 -> "c", 200, 200 object 4 -> "b", 400, 0 

will be sorted as object 3, object 1, object 4, object 2

We apologize if this has already been answered - please indicate me this post, because I could not find it.

+4
source share
4 answers
 list.OrderByDescending(o => o.Field2) .ThenByDescending(o => o.Field1); 
+6
source
 var ordered = objects.OrderByDescending(o => o.SecondDec) .ThenByDescending(o => o.FirstDec); 

Then list it or create another collection, for example. through ToList .

 foreach(var obj in ordered) { // ... } 
+4
source

Other answers show a great way to build an IEnumerable <T> which, when enumerated, displays the items in your list in the order you describe. It provides a "view" of the list, so to speak, and does not change the order of elements in the list itself.

If you really want to sort the list (i.e. change the list in place so that its elements are in order), you can use the List <T> Sort Method as follows:

 list.Sort((x, y) => { int result = decimal.Compare(y.SecondDecimal, x.SecondDecimal); if (result == 0) result = decimal.Compare(x.FirstDecimal, y.FirstDecimal); return result; }); 
+4
source

Use OrderByDescending and ThenBy :

 var sorted = items.OrderByDescending(item => item.Decimal2) ThenBy(item => item.Decimal1); 
+1
source

Source: https://habr.com/ru/post/1498673/


All Articles