Home > Blockchain >  How can I Sort List in Dictionary? C#
How can I Sort List in Dictionary? C#

Time:03-12

I would like to sort my List elements based on Amount property and create a new sorted Dictionary. Is it possible with Lambda expression? If yes could you show me an example?

Code:

internal class Loss
{
    string name;
    double amount;
    double cost;

    public string Name { get => name; set => name = value; }
    public double Amount { get => amount; set => amount = value; }
    public double Cost { get => cost; set => cost = value; }

    public Loss(string name, double amount, double cost)
    {
        Name = name;
        Amount = amount;
        Cost = cost;
    }
}
internal class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, List<Loss>> unitLossDict = new Dictionary<string, List<Loss>>()
        {

                    {   "Unit1",new List<Loss>() { new Loss("welding",1.2,500),
                    new Loss("drilling", 2.2, 500),
                    new Loss("housing", 0.2, 100) }},
                    {   "Unit2",new List<Loss>() { new Loss("welding",0.01,10),
                    new Loss("drilling", 3.2, 500),
                    new Loss("housing", 9.2, 800) }}


        };

        Dictionary<string, List<Loss>> sortedUnitLossDict = unitLossDict;


    }
}

CodePudding user response:

Import System.Linq and try below code.

Dictionary<string, List<Loss>> SortedDictionary = new Dictionary<string, List<Loss>>();
        foreach (var key in unitLossDict.Keys)
        {
            SortedDictionary.Add(key, unitLossDict[key].OrderBy(i => i.Amount).ToList());
        }
  • Related