按值排序id并形成字符串

时间:2016-06-30 08:12:41

标签: c# sorting

我有一个进程,在运行时输出一个唯一的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;
    }

我只是想知道这是最有效的做事方式还是有更快的方法。评论/建议/代码样本非常感谢。 谢谢。 学家

1 个答案:

答案 0 :(得分:4)

您只需使用一些LINQ和字符串实用程序就可以做到这一点:

public static string SortAndConvertToString(Hashtable ht)
{
    var keysOrderedByValue = ht.Cast<DictionaryEntry>()
        .OrderBy(x => x.Value)
        .Select(x => x.Key);

    return string.Join(";", keysOrderedByValue);
}

有关正常工作的演示,请参阅this fiddle

我建议您使用通用Dictionary<int, double>而不是Hashtable。请参阅this related question