【问题标题】:Finding matched values in dictionary with list?在带有列表的字典中查找匹配的值?
【发布时间】:2013-06-12 23:23:49
【问题描述】:

我有以下字典:

Dictionary<int, List<TypeA>> dict

并添加了对象:

dict.Add(1, new List<TypeA>{TypeA.1, TypeA.2, TypeA.3};
dict.Add(11, new List<TypeA>{TypeA.2, TypeA.6, TypeA.7};
dict.Add(23, new List<TypeA>{TypeA.3, TypeA.4, TypeA.9};

使用单行语法 (lambdas),我如何在整个字典中找到任何 TypeA.3?

这将被封装到一个返回布尔值的方法中。真 == 匹配,假 == 不匹配。以上将返回 true。

【问题讨论】:

    标签: c#-4.0 dictionary generic-list


    【解决方案1】:

    这里有一些受 Reed 启发的工作代码。

    您可以将其弹出到 LINQPad 中并查看它的运行情况。通过http://linqpad.com 获取 LINQPad,它会有所帮助!

        static bool CheckIT(Dictionary<int, List<TypeA>> theList, TypeA what)
        {
            return theList.Any(dctnry => dctnry.Value.Any(lst => lst == what));
        }
    
        public static void Main()
        {
            Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
    
            dict.Add(1, new List<TypeA>{TypeA.1, TypeA.2, TypeA.3};
            dict.Add(11, new List<TypeA>{TypeA.2, TypeA.6, TypeA.7};
            dict.Add(23, new List<TypeA>{TypeA.3, TypeA.4, TypeA.9};
    
            if (CheckIT(dict,TypeA.3 ))
             Console.WriteLine("Found");
            else
              Console.WriteLine("Lost");
        }
    

    您也可以更进一步,制作一个通用版本,例如

        static bool CheckIT<T>(Dictionary<int, List<T>> theList, T what) where T : IEquatable<T>
        {
            return theList.Any(dict => dict.Value.Any(l => l.Equals(what)));
        }
    

    那你会说

       if (CheckIT<TypeA>(dict,TypeA.3 ))
    

    但你也可以说

       if (CheckIT<int>(dict,13 ))
    

    因为我没有定义 TypeA。

    【讨论】:

      【解决方案2】:

      如果您只是想查看TypeA.3 是否存在于任何地方,您可以使用:

      bool exists = dict.Values.Any(v => v.Any(t => t == TypeA.3));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        相关资源
        最近更新 更多