2016-06-30 22 views
2

我有一個進程,在運行時輸出一個唯一的int ID和一個不一定唯一的double值。例如:按值排序id並形成一個字符串

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.

+0

您的示例輸出不正確。它應該是'45; 23; 26; 25'。 –

回答

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