2014-02-14 34 views
0

我有一個巨大的字符串集合。我會更頻繁地找出所有以給定角色開頭的字符串。什麼是最好的收集來做到這一點。我將按排序順序初始化集合。收集字符串的最佳數據結構在C#

感謝

+0

你在用什麼字符串? – Liath

+0

有多少是「巨大的」? – Larry

+0

您是否使用字符串集合作爲建議列表? – Jaihind

回答

0

如果你需要用字符串的巨大集合定期搜索,然後用哈希表。請記住平均分配表以加快查找操作。

+0

我認爲哈希表是不可用在Windows Phone8 – Kumaran

1

如果你想從一個角色到該角色開始的所有字符串的映射,你可能會發現ILookup<TKey, TElement>合適。這是非常類似於一個Dictionary<TKey, TValue>,有兩個主要差別:

  1. 代替1:1映射,它執行1:n的映射(即,可以存在每個鍵一個以上的值)。

  2. 無法實例(new),也不填充它(.Add(…))自己;相反,您讓.NET通過在後者上調用.ToLookup(…)從另一個集合中派生出一個完全填充的實例。

以下是如何建立這樣一個1一個例子:N地圖:

using System.Collections.Generic; // for List<T> 
using System.Linq;     // for ILookup<TKey, TValue> and .ToLookup(…) 

// This represents the source of your strings. It doesn't have to be sorted: 
var strings = new List<string>() { "Foo", "Bar", "Baz", "Quux", … }; 

// This is how you would build a 1:n lookup table mapping from first characters 
// to all strings starting with that character. Empty strings are excluded: 
ILookup<char, string> stringsByFirstCharacter = 
    strings.Where(str => !string.IsNullOrEmpty(str)) // exclude empty strings 
      .ToLookup(str => str[0]);     // key := first character 

// This is how you would look up all strings starting with B. 
// The output will be Bar and Baz: 
foreach (string str in stringsByFirstCharacter['B']) 
{ 
    Console.WriteLine(str); 
} 

PS:ILookup<…>(接口)以上超鏈接指向你的幫助頁面Lookup<…>(實現類)。這是有目的的,因爲我發現這個類的文檔更容易閱讀。不過,我會推薦在你的代碼中使用這個接口。

+0

這不適合我的情況。這些詞不是英文單詞。單個字母將組合多個字母。所以我會在情況下返回所有單詞,如果與其他人結合.. – Kumaran

+0

@Kumaran:那麼,你不*必須*從'字符'到'字符串'的地圖。你也可以從'string'映射到'string's,允許你選擇任意長的前綴而不是隻有單個字符(Unicode代碼點)。您必須將類型更改爲'ILookup ',並且您需要將提取第一個字符的'.ToLookup(...)'lambda替換爲一個提取字符串前綴的lambda。 – stakx

0

那麼你需要創建一個索引函數的字符串。

此ID的建議使用

Dictionary<string,List<string>>數據結構。

ToLookup不太好,因爲它限制了你的數據結構的管理能力。

+0

我不能分開這樣的話。那麼它會使我的其他操作複雜化。 – Kumaran