How to sort my List

Kavithma 26 Reputation points
2021-10-25T14:02:46.367+00:00

HI all,
I have a below list

var listItems = new List<Item>
{
new Item() { OrderValue= 100, Balance= 90},
new Item() { OrderValue= 100, Balance= 70},
new Item() { OrderValue= 100, Balance= 0},
new Item() { OrderValue= 6, Balance= 0},
};

I need to sort the above list and get the below results

OrderValue= 100, Balance= 90 // 1st as OrderValue - Balance Difference is =10 and this value is high priority in asc order in the list
OrderValue= 100, Balance= 80 // 2nd as OrderValue - Balance Difference is =20 and this value is high priority in asc order in the list
OrderValue= 6, Balance= 0 // 3rd as OrderValue - Balance Difference is =6 but this willd not be prioratised first in the list becasue of the OrderValue is less compared to the two other list items above
OrderValue= 100, Balance= 0 // 4th as OrderValue - Balance Difference is = 100 and this will be the last priority as highst value for this should be at the last.

so how do we sort my list to get the above reslts ?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,221 questions
0 comments No comments
{count} vote

Accepted answer
  1. Maheswari Sivanandam 76 Reputation points
    2021-10-25T14:49:47.83+00:00

    just add SortingField in your Item class

    public class Item
    {
    public int OrderValue { get; set; }
    public int Balance { get; set; }
    public int SortingField {
    get
    {
    return this.OrderValue - this.Balance;
    }
    }

    }

    then use the following coding to meet your sorting needs,

    var sortedList = listItems.OrderByDescending(q => q.Balance).ThenBy(q=>q.SortingField).ToList();


2 additional answers

Sort by: Most helpful
  1. Maheswari Sivanandam 76 Reputation points
    2021-10-25T14:25:31.227+00:00

    use the following code to sort the list based on id property,
    var sortedList = listItems.OrderBy(q => q.id).ToList();


  2. Kavithma 26 Reputation points
    2021-10-25T15:22:41.157+00:00

    Thanks for helping me this , I will test this and update you :)

    0 comments No comments