Question

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));
Was it helpful?

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();

OTHER TIPS

The statement alpha.OrderByDescending(x => x.Value); has no effect... Linq operators are lazy, they're not executed until you enumerate their result. Since you're not using the result of OrderByDescending, it just creates a lazy sequence that would yield the items of alpha sorted by value, if you enumerated it... OrderByDescending doesn't sort the collection, it just returns a sorted sequence of items from the collection, without modifying the collection itself.

You should do it like this:

foreach (var a in alpha.OrderByDescending(x => x.Value))
    A.Add(a.Key + ":" + a.Value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top