输出格式如下:
0.8765432
0.7654323
1.0987234
.......
我必须得到这样的结果:
1 1.0987234
2 0.8765432
3 0.7654323
...
我写了下面的脚本来将我的数据存储在哈希表中并对其进行排序。我必须基于该值对它进行排序(降序)并仅提取n个最高值(键和值)。
if (sc >= 0 && sc <= 89395)
{
for (int z = 0; z <= 1143600; z++)
{
dotproduct(sc, z); // is a function to multiply to float
hashtable.Add(z, result);
}
SortedDictionary<int, float> dict = new SortedDictionary<int, float>(hashtable);
dict.OrderByDescending(x => x.Key).Take(n);
foreach (int key in dict)
{
System.Console.WriteLine(String.Format("{0}: {1}", key, dict[key]));
}
}
我有两个问题:
根据您的评论,我建议您也可以使用简单的方法List<float>
(如果dotproduct的结果为浮点型)。ASortedDictionary<int, float>
没有意义,因为您只插入循环的索引和dotproduct的结果。因此,aList<float>
具有相同的目的,并且需要较少的内存。如果以后想知道第3次运行的结果,只需访问列表的索引器即可,如var resultFor3rdRun = list[2]
。
在编写时,原始索引在输出数据时很重要。您必须先存储此索引。您可以使用Select
提供索引的Linq扩展方法的重载来执行此操作。然后,您可以按降序对它们进行排序,并获取要显示的项目数(例如,前10个):
if (sc >= 0 && sc <= 89395)
{
var results = new List<float>(1143600); // Specify number of items upfront for better performance
for (int z = 0; z <= 1143600; z++)
{
results.Add(dotproduct(sc, z)); // is a function to multiply to float
}
foreach(var resultWithIndex in results
.Select((x, index) => new { Result = x, Index = index})
.OrderByDescending(x => x.Result)
.Take(10))
{
System.Console.WriteLine(String.Format("{0}: {1}",
resultWithIndex.Index,
resultWithIndex.Result));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句