【问题标题】:Sorting an id by value and forming a string按值对 id 进行排序并形成字符串
【发布时间】: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

标签: c# sorting


【解决方案1】:

您可以非常简单地使用一些 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&lt;int, double&gt; 而不是 Hashtable。见this related question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多