2011-02-08 82 views
4

我有一些與double值相關的字符串。我需要能夠通過值輕鬆地對它們進行排序,並輕鬆地將字符串作爲某種列表。這些對可能有100k +。字典或列表

所以,我的問題是我是否應該使用帶有字符串的字典作爲鍵和雙精度值或具有相同鍵和值的KeyValuePair的List?

在詞典中的情況下,很容易通過

dict.Keys.toList()

領取鑰匙的列表,在列表中的情況下,很容易通過值通過

list.Sort(delegate(KeyValuePair x, KeyValuePair y) { return y.Value.CompareTo(x.Value); })進行排序。

雖然我還沒找到一種辦法。你有什麼建議?

+2

選擇所有的串1周的方式都是雙重價值獨特之處? – 2011-02-08 16:51:04

+1

除了@Matt Ellen的問題,你需要通過字符串鍵進行查找嗎?你只是說按價值排序,並得到字符串,但沒有關於你是否正在查找。 – jason 2011-02-08 16:54:34

回答

1

這裏爲1的值來選擇都在你的鍵值列表中的字符串或從keyvaluepair

List<string> onestrings = list.Where(a=>a.Value == 1).Select(a => a.Key).ToList(); 
List<string> allstrings = list.Select(a => a.Key).ToList(); 
0

我假設你有一個以上的字符串給定的double值。

你可以仍然這樣做的另一種方式:Dictionary<double, list<string>>

所以你會採取雙重價值的關鍵,當你得到一個字符串用相同的雙重價值,你把它添加到列表中。

通過這種方式,您可以獲得字典的查找速度,並且您仍然可以在需要時執行某種鍵。

1

其中一個主要考慮因素是您的值是否是唯一的。如果它們不是,字典將不起作用,因爲它需要唯一的密鑰。這也將更難以分類。

如果您只是使用它來存儲值對,並且沒有唯一性約束,我個人會使用List<Tuple<double,string>>

3

我會推薦一個SortedList<double, string>。這聽起來像正是你想要的:

  • double值自動排序(在Keys屬性)
  • 字符串是通過Values財產,以無障礙

這將只有當你的工作當然,double的值是唯一的。否則,可能會在自己的收藏緊裹SortedList<double, List<string>>,是這樣的:

class DoubleStringList 
{ 
    SortedList<double, List<string>> _strings = new SortedList<double, List<string>>(); 

    public void Add(string str, double value) 
    { 
     List<string> list; 
     if (!_strings.TryGetValue(value, out list)) 
     { 
      _strings[value] = list = new List<string>(); 
     } 

     list.Add(str); 
    } 

    public IEnumerable<KeyValuePair<double, string>> GetEntries() 
    { 
     var entries = from entry in _strings 
         from str in entry.Value 
         select new KeyValuePair<double, string>(entry.Key, str); 

     return entries; 
    } 
} 
0

怎麼樣Lookup

Dictionary<string,double> dic = new Dictionary<string,double>(); 
ILookup<double,string> lookup = dic.ToLookup(kvp => kvp.Value, kvp => kvp.Key);