C# Linq 结果 ToDictionary 帮助

发布于 2024-08-16 09:05:05 字数 627 浏览 2 评论 0原文

我有一个从字典中获取结果的 lambda 表达式。

var sortedDict = (from entry in dctMetrics 
                  orderby entry.Value descending 
                  select entry);

该表达式拉回我需要的对,我可以在 IDE 的调试模式中看到它们。

如何将其转换回与源类型相同的字典?我知道 SortedDict 的 TElement 是 KeyValuePair,但我无法完全理解 ToDictionary 扩展方法的语法。我还尝试对 var 结果进行 foreach'ing 来分段构造一个新字典,但无济于事。

有没有这样的东西(功能方面):

var results = (from entry in dictionary 
               orderby entry.Value descending 
               select entry);
Dictionary<string,float> newDictionary = results as (Dictionary<string,float>);

I have a lambda expression that gets results from a Dictionary.

var sortedDict = (from entry in dctMetrics 
                  orderby entry.Value descending 
                  select entry);

The expression pulls back the pairs I need, I can see them in the IDE's debug mode.

How do I convert this back a dictionary of the same type as the source? I know sortedDict's TElement is a KeyValuePair, but I am having trouble fully understanding the ToDictionary extension method's syntax. I also tried foreach'ing the var result to piecewise construct a new dictionary, but to no avail.

Is there something like this (functionality wise):

var results = (from entry in dictionary 
               orderby entry.Value descending 
               select entry);
Dictionary<string,float> newDictionary = results as (Dictionary<string,float>);

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

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

发布评论

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

评论(1

柏拉图鍀咏恒 2024-08-23 09:05:05

您可以这样做:

var newDictionary = results.ToDictionary(r => r.Key, r => r.Value);

将其读作“对于结果中的每一对,将该元素添加到新字典中,其中键将作为该对的键生成,值将作为该对的值生成”。

另外,仅基于您的示例代码 - 您应该记住 Dictionary 是作为哈希表实现的,因此它不会维护您放置的元素的顺序进入其中。如果您需要有序映射,请考虑使用 SortedDictionarySortedList

You can do it like this:

var newDictionary = results.ToDictionary(r => r.Key, r => r.Value);

Read that as "for each pair in results, add that element to the new dictionary, where the key will be produced as the key of the pair, and the value will be produced as the value of the pair."

Also, just based on your sample code -- you should keep in mind that a Dictionary<T, U> is implemented as a hash table, so it won't maintain the order of the elements you put into it. Consider using a SortedDictionary or a SortedList instead if you need an ordered map.

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