【发布时间】:2016-06-30 08:12:40
【问题描述】:
我有一个进程在运行时输出一个唯一的 int ID 和一个不一定是唯一的 double 值)。例如:
ID、值 23, 56000 25, 67000 26、67000 45, 54000
我必须捕获这些并通过增加值(从小到大)对 ID 进行排名,然后形成以下形式的字符串:id1、id2、id3 等... 因此,在上述情况下,输出将是:45;26;25;23
永远不会有大量的 ID - 但假设每次通过 10 个。
我的方法是使用哈希表来捕获值。排序代码如下:
/// <summary>
/// Converts a hashtable (key is the id; value is the amount) to a string of the
/// format: x;y;z; where x,y & z are the id numbers in order of increasing amounts
/// cf. http://stackoverflow.com/questions/3101626/sort-hashtable-by-possibly-non-unique-values for the sorting routine
/// </summary>
/// <param name="ht">Hashtable (key is id; value is the actual amount)</param>
/// <returns>String of the format: x;y;z; where x,y & z are the id numbers in order of increasing amounts</returns>
public static string SortAndConvertToString(Hashtable ht)
{
if (ht.Count == 1)
return ht.Keys.OfType<String>().FirstOrDefault() +";";
//1. Sort the HT by value (smaller to bigger). Preserve key associated with the value
var result = new List<DictionaryEntry>(ht.Count);
foreach (DictionaryEntry entry in ht)
{
result.Add(entry);
}
result.Sort(
(x, y) =>
{
IComparable comparable = x.Value as IComparable;
if (comparable != null)
{
return comparable.CompareTo(y.Value);
}
return 0;
});
string str = "";
foreach (DictionaryEntry entry in result)
{
str += ht.Keys.OfType<String>().FirstOrDefault(s => ht[s] == entry.Value) + ";";
}
//2. Extract keys to form string of the form: x;y;z;
return str;
}
我只是想知道这是最有效的做事方式还是有更快的方式。非常感谢评论/建议/代码示例。 谢谢。 J.
【问题讨论】:
-
您的示例输出不正确。应该是
45;23;26;25。