输出的格式是这样的:
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]));
}
}
我有两个问题:
- 我用来制作哈希表和排序的方法是否正确?
- 如何提取n个最上面的值来显示?
根据您的评论,我建议您也可以使用一个简单的List<float>
(如果 dotproduct 的结果是浮点数)。SortedDictionary<int, float>
没有意义,因为您只插入循环的索引和点积的结果。因此,List<float>
具有相同的目的,并且需要更少的内存。如果以后想知道第三次运行的结果,只需访问列表的索引器,如 var resultFor3rdRun = list[2]
。
在编写时,原始索引在输出数据时很重要。您必须在之前存储此索引;可以使用提供索引的 Linq Select
扩展方法的重载来执行此操作。之后,您可以按降序对它们进行排序,并获取要显示的项目数(例如前 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));
}
}