1

I have the following dictionary:

Dictionary<int, List<TypeA>> dict

And have added objects:

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};

Using a single line of syntax (lambdas), how do I find any TypeA.3 in the entire dictionary?

This will be encapsulated into a method that returns a bool. True == match and false == no match. The above would return true.

4

2 回答 2

1

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

bool exists = dict.Values.Any(v => v.Any(t => t == TypeA.3));
于 2013-06-12T23:28:22.180 回答
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 一样。

于 2013-06-12T23:29:55.440 回答