带值的 SortedList 和带 lambda 的简化循环

发布于 2024-12-31 23:51:32 字数 587 浏览 1 评论 0原文

我这里有一段代码:

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); 不按值排序,而是按键排序。我可以知道代码有什么问题吗?

  2. 我可以简化一下:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事灯 2025-01-07 23:51:32

语句 alpha.OrderByDescending(x => x.Value); 无效...Linq 运算符是惰性的,它们在您枚举其结果之前不会执行。由于您没有使用 OrderByDescending 的结果,它只是创建一个惰性序列,会生成按值排序的 alpha 项,< em>如果您枚举它...OrderByDescending 不会对集合进行排序,它只是从集合中返回已排序的项目序列,而不修改集合本身。

你应该这样做:

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

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);
ヤ经典坏疍 2025-01-07 23:51:32

这可能有帮助:

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

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文