Search code examples
c#listlambdasortedlist

SortedList with value and simplified loops with lambda


I have a block of codes here:

SortedList<char, int> alpha = new SortedList<char, int>();
List<string> A = new List<string>();
alpha.OrderByDescending(x => x.Value);
foreach (var a in alpha)
    A.Add(a.Key + ":" + a.Value);
  1. alpha.OrderByDescending(x => x.Value); doesn't sort by value, but sorts by key. May I know what's the problem with the code?

  2. can I simplify:

    foreach (var a in alpha) A.Add(a.Key + ":" + a.Value);

into one lambda statement? something like

alpha.ForEach(x => A.Add(a.Key + ":" + a.Value));

Solution

  • This might help:

    SortedList<char, int> alpha = new SortedList<char, int>();
    alpha.Add('B',1);
    alpha.Add('A',2);
    alpha.Add('C',3);
    var A= alpha.OrderByDescending(a =>a.Value)
            .Select (a =>a.Key+":"+a.Value)
            .ToList();