2014-12-03 82 views
0

這裏的一個是我的代碼:如何搜索三重元素(key_value對字典)他們

public class PairedKeys 
{ 
    public byte Key_1 { get; set; } 
    public byte Key_2 { get; set; } 

    public PairedKeys(byte key_1, byte key_2) 
    { 
     Key_1 = key_1; 
     Key_2 = key_2; 
    } 
} 

public static class My_Class 
{ 
    static Dictionary<PairedKeys, char> CharactersMapper = new Dictionary<PairedKeys, char>() 
    { 
     { new PairedKeys(128, 48), 'a' }, 
     { new PairedKeys(129, 49), 'b' } 
    } 
} 

我怎樣才能獲得通過搜索Key_2CharactersMapper價值?

這裏是我的嘗試:

for (int j = 0; j < CharactersMapper.Count; j++) 
{ 
    try 
    { 
     char ch = CharactersMapper[new PairedKeys(????, Key_2)]; 
    } 
    catch 
    { 
    } 
} 
+1

可能要清理你的代碼了,因此編譯。您的'PairedKeys' ctor缺少圓括號,字典缺少分號。 – 2014-12-03 17:33:16

回答

1

使用LINQ,你可以做以下返回單個項目:

var ch = CharactersMapper.Single(cm => cm.Key.Key_2 == 49); 

或者,如果你希望一個以上的項目:

var chList = CharactersMapper.Where(cm => cm.Key.Key_2 == 49); 

它們都將返回一個KeyValuePair<‌​Classes.PairedKeys,char>IEnumerable<KeyValuePair<‌​Classes.PairedKeys,char>>正如你在評論中指出的那樣。如果你想獲得在剛剛char內容,您可以使用Select方法:

//Single char 
char singleChar = CharactersMapper.Single(cm => cm.Key.Key_2 == 49).Select(c => c.Value); 

//list of chars 
IList<char> charList = CharactersMapper.Where(cm => cm.Key.Key_2 == 49).Select(c => c.Value).ToList(); 
+0

在這裏的錯誤:錯誤不能隱式轉換類型'System.Collections.Generic.IEnumerable >'到'char' – MoonLight 2014-12-03 17:42:09

+0

我也試過這個:ch_ar [i] = char.Parse(CharactersMapper.Where(cm => cm.Key.Arabic_Byte == charByte)); - >該錯誤仍然存​​在... – MoonLight 2014-12-03 17:44:02

+0

@MoonLight是的,上面將返回一個'KeyValuePair '。我會更新答案,包括如何獲得'char' – 2014-12-03 18:52:08

2

以這種方式使用字典,還有的不會是一個優化的(即O(1))實現這一目標的方式。你可以,但是,剛剛經歷,環這將是O(n)

var result = dictionary.Where(d => d.Key.Key_2 == 3); 

假設你正在尋找,當然對於3

+0

P.s. 'Key_2'對於一個屬性來說不是一個很好的C#py名字 - 我只想簡單地使用'Key2'。 – 2014-12-03 17:36:11

+0

好的,謝謝。我要解決它們。 – MoonLight 2014-12-03 17:37:50

+0

@MoonLight另外我想你會想在你使用普通的'dictionary [key]'語法時使'PairedKey'成爲一個結構並重寫'GetHashCode'和'Equals'以獲得最佳性能。 – 2014-12-03 17:40:37