如何从Dictionary <string,object> </string,object>获取值

时间:2015-04-03 06:48:39

标签: c# linq

我有一个字典,我想要检索与列表

匹配的结果

这是我到目前为止所做的事情

         Dictionary<string, Dictionary<string, int>> SomeDictionary = new Dictionary<string, Dictionary<string, int>>();
        List<int> MyList = new List<int>()
        {

            2,3,4,5
        };

        Dictionary<string, int> internalDictionary = new Dictionary<string, int>();
        internalDictionary.Add("two", 2);
        internalDictionary.Add("three", 3);
        internalDictionary.Add("four", 4);
        internalDictionary.Add("five", 5);

        Dictionary<string, int> AnotherDictionary = new Dictionary<string, int>();
        AnotherDictionary.Add("six", 6);
        AnotherDictionary.Add("three", 3);
        AnotherDictionary.Add("seven", 7);


        SomeDictionary.Add("Dictionary1", internalDictionary);
        SomeDictionary.Add("Dictionary2", AnotherDictionary);


        var res = from l in MyList
                  select(from q in
                  (from p in
                       (from s in SomeDictionary
                        select s)
                   select p) where q.Value.Equals(l) select q);

返回的值为null。我想念的是什么?

我需要匹配KeyValuePair,其中值与内部字典值匹配。

2 个答案:

答案 0 :(得分:3)

说明:

  1. 选择“多个”可将所有内部词典合并到“一体化”词典中。
  2. List和SelectMany是IEnumerable。因此可以在IEnumerable对象之间进行连接。
  3. 但是,List包含字符串值,而从SelectMany返回的IEnumerable对象具有整数值。
  4. 在将整数转换为字符串后,使用字符串和整数值创建了内部连接查询。参考可能需要输出的截屏视频

    Screen cast showing working code

    此Linq代码段可能会有所帮助:

    var allinone = (from l in MyList
                           join d in SomeDictionary.SelectMany(s => s.Value) on l equals d.Value
                           select d);
    

答案 1 :(得分:1)

试试这个:

    var res = from l in MyList
              from q in SomeDictionary
              from w in q.Value
              where w.Value == l
              select w;

我明白了:

res