日期:2014-05-20  浏览次数:21069 次

Dictionary中如何用键查找值,或值查找键?
如题,有这样一个波特率的Dictionary  
Dictionary<int, int> Dic_BandRate = new Dictionary<int, int>()
{
  {10,115200},{11,57600},{12,38400},{13,19200},{14,9600},{15,4800}
};
如何根据上层传来的9600,找到14这个值,总感觉一句话就可以觉得的,还是没实现,谢谢各位!

------解决方案--------------------
探讨
C# code

void Main()
{
Dictionary<int, int> Dic_BandRate = new Dictionary<int, int>()
{
{10,115200},{11,57600},{12,38400},{13,19200},{14,9600},{15,4800}
};
var query=from d……

------解决方案--------------------
这样就可以了吧:

var key = Dic_BandRate.Single(k => k.Value == 9600).Key;

如果有可能值不存在,那么就用SingleOrDefault
var keyvaluepair = Dic_BandRate.SingleOrDefault(k => k.Value == 9600);

var key = keyvaluepair == null ? 0 : keyvaluepair.Key;


------解决方案--------------------
给出我自己的思路
C# code

 Dictionary<int, int> Dic_BandRate = new Dictionary<int, int>()
                {
                {10,115200},{11,57600},{12,38400},{13,19200},{14,9600},{15,4800}
                };
            var query = from d in Dic_BandRate
                        where d.Value == 9600
                        select d.Key;
            Console.WriteLine(query.FirstOrDefault());