C# Linq 结果 ToDictionary 帮助
我有一个从字典中获取结果的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样做:
将其读作“对于结果中的每一对,将该元素添加到新字典中,其中键将作为该对的键生成,值将作为该对的值生成”。
另外,仅基于您的示例代码 - 您应该记住
Dictionary
是作为哈希表实现的,因此它不会维护您放置的元素的顺序进入其中。如果您需要有序映射,请考虑使用SortedDictionary
或SortedList
。You can do it like this:
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 aSortedDictionary
or aSortedList
instead if you need an ordered map.