[英]Sorting an id by value and forming a string
我有一个进程,在运行时会输出一个唯一的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.
您可以使用LINQ和字符串实用程序非常简单地完成此操作:
public static string SortAndConvertToString(Hashtable ht)
{
var keysOrderedByValue = ht.Cast<DictionaryEntry>()
.OrderBy(x => x.Value)
.Select(x => x.Key);
return string.Join(";", keysOrderedByValue);
}
请参阅此小提琴以获得有效的演示。
我建议您使用通用的Dictionary<int, double>
而不是Hashtable
。 请参阅此相关问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.