带值的 SortedList 和带 lambda 的简化循环
我这里有一段代码:
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);
不按值排序,而是按键排序。我可以知道代码有什么问题吗?我可以简化一下:
foreach(alpha 中的 var a) A.Add(a.Key + ":" + a.Value);
到一个 lambda 语句中?类似的东西
alpha.ForEach(x => A.Add(a.Key + ":" + a.Value));
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));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
语句 alpha.OrderByDescending(x => x.Value); 无效...Linq 运算符是惰性的,它们在您枚举其结果之前不会执行。由于您没有使用
OrderByDescending
的结果,它只是创建一个惰性序列,会生成按值排序的alpha
项,< em>如果您枚举它...OrderByDescending
不会对集合进行排序,它只是从集合中返回已排序的项目序列,而不修改集合本身。你应该这样做:
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 ofOrderByDescending
, it just creates a lazy sequence that would yield the items ofalpha
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:
这可能有帮助:
This might help: