Reputation: 331
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);
alpha.OrderByDescending(x => x.Value);
doesn't sort by value, but sorts by key. May I know what's the problem with the code?
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));
Upvotes: 0
Views: 1828
Reputation: 31239
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();
Upvotes: 2
Reputation: 292465
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);
Upvotes: 3