2014-12-03 20 views
-2

這裏是我的代碼:如何搜索三重元素(key_value對詞典)的其中之一 - IEnumerable的錯誤

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

    public PairedKeys(byte key1, byte key2) 
    { 
     Key_1 = key1; 
     Key_2 = key2; 
    } 
} 

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_2爲字符的CharactersMapper價值?

這裏是我的嘗試:

byte b = 48; 
char ch = CharactersMapper.Where(d => d.Key.Key_2 == b); 

和錯誤:

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<PairedKeys,char>>'

+0

只需要注意一下'PairedKeys':當'struct'比'class'更好時,情況就是如此。 – Dennis 2014-12-03 18:37:49

+3

你在這段代碼中沒有使用索引器。還有一些其他的錯誤,但實際的錯誤應該在別的地方 – 2014-12-03 18:41:36

+2

Where()'子句返回IEnumerable >',而不是一個' char'值。 – PoweredByOrange 2014-12-03 18:42:27

回答

1

我不知道你是如何得到了精確的錯誤消息。問題是Where子句返回一個KeyValuePair,而不是char。下面的單元測試通過,並演示解決方案(首先你必須CharactersMapper靜態變量更改爲公共):

[TestMethod] 
public void Testing() 
{ 
    byte b = 48; 
    var item = My_Class.CharactersMapper 
         .Where(d => d.Key.Key_2 == b) 
         .FirstOrDefault(); 

    Assert.IsNotNull(item, "not found"); 

    char ch = item.Value; 
    Assert.AreEqual('a', ch, "wrong value found"); 
} 
1

這工作

byte b = 48; 
char ch = My_Class.CharactersMapper.First(d => d.Key.Key_2 == b).Value; 

你仍然需要一些錯誤處理的情況下,當鍵不存在。