0

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;


    }
}
fetike89
  • 5
  • 2
  • 1
    FYI you might want to read about [auto properties](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties) and [records](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records) – juharr Mar 11 '22 at 15:32
  • 2
    A Dictionary has no sort. Do you meant sorting the lists in the Dictionary? – Ralf Mar 11 '22 at 15:34
  • Have you tried `foreach (var list in sortedUnitLossDict.Values) list.Sort(/*...*/);` – Wyck Mar 11 '22 at 15:39
  • [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – JonasH Mar 11 '22 at 15:40

1 Answers1

0

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());
        }
anoop
  • 3,812
  • 2
  • 16
  • 28