【发布时间】:2010-03-26 14:16:39
【问题描述】:
所以我正在尝试更多地了解 lambda 表达式。我在 stackoverflow 上阅读了this question,同意所选答案,并尝试使用 C# 中的控制台应用程序使用简单的 LINQ 表达式来实现该算法。
我的问题是:如何将 lambda 表达式的“var 结果”转换为可以打印的可用对象?
如果我声明outer => outer.Value.Frequency 时,我也希望能深入解释发生的事情
(我已经阅读了很多关于 lambda 表达式的解释,但进一步的澄清会有所帮助)
C#
//Input : {5, 13, 6, 5, 13, 7, 8, 6, 5}
//Output : {5, 5, 5, 13, 13, 6, 6, 7, 8}
//The question is to arrange the numbers in the array in decreasing order of their frequency, preserving the order of their occurrence.
//If there is a tie, like in this example between 13 and 6, then the number occurring first in the input array would come first in the output array.
List<int> input = new List<int>();
input.Add(5);
input.Add(13);
input.Add(6);
input.Add(5);
input.Add(13);
input.Add(7);
input.Add(8);
input.Add(6);
input.Add(5);
Dictionary<int, FrequencyAndValue> dictionary = new Dictionary<int, FrequencyAndValue>();
foreach (int number in input)
{
if (!dictionary.ContainsKey(number))
{
dictionary.Add(number, new FrequencyAndValue(1, number) );
}
else
{
dictionary[number].Frequency++;
}
}
var result = dictionary.OrderByDescending(outer => outer.Value.Frequency);
// How to translate the result into something I can print??
有关打印命令的完整答案,请参阅my answer here。
【问题讨论】:
-
通过观看 Jon Skeet 的演讲,我了解了很多关于 LINQ 的工作原理,请参阅此页面了解更多信息 csharpindepth.com/Talks.aspx。我认为这是第 6 节,但它们都非常有用。
-
@Matt - 谢谢,我去看看!
标签: c# lambda type-inference