2014-12-03 85 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