C#确定Dictionary是否包含所有一组值

时间:2016-10-08 15:12:12

标签: c# dictionary arraylist

我有以下字典:

Dictionary<string, ArrayList> vertices = new Dictionary<string, ArrayList>();
vertices.Add("Key1",stringarray1);
vertices.Add("Key2",stringarray2);
vertices.Add("Key3",stringarray3);

现在我想知道如果检查每个字典的其他键(如"Key2""Key3"),如果它们的值包含其中一个或全部来自"Key1"的值(ArrayList)的值,但不起作用。这可能是非常直接的,但我无法得到它

var values = (ArrayList)vertices["Key1"];
foreach (var val in vertices)
{
    if (val.Key != "Key1" && val.Value.Contains(values))
    {
        //do something here
    }
}

4 个答案:

答案 0 :(得分:1)

您无法将集合传递给contains方法,而是将单个元素传递给它。因此,您需要迭代key1数组中的元素,并检查另一个数组是否也包含它。

var key1Val = vertices["key1"];
 foreach (var val in vertices)
        {
            if(val.Key != "key1")
            {
               bool exist = false;
               foreach (var element in val.Value) {
                      if(key1Val.Contains(element)){
                            exist = true;
                            break;
                      }
                 }
                  if(exist){        /*do stuff*/}
                //do something here
            }
        }

答案 1 :(得分:1)

var key1Values;
if (!vertices.TryGetValue("Key1", out key1Values)) {   
   return; 
}

foreach(KeyValuePair<string, ArrayList> entry in vertices)
{
    if((entry.Key == "Key2" || entry.Key == "Key3") && entry.Value.Any(item => key1Values.Contains(item) )
    {
       //do some work
    }
}

答案 2 :(得分:1)

问题在于您将错误的内容传递给ContainsContains应该接收要在集合中查找的项目,但是您要传递整个集合。由于您使用的是ArrayList,其中项目存储为object,您没有收到编译时错误,但它无法正常工作(并且使用object对项目进行比较比较哪个是检查参考文献。

您可以使用Linq这样做:

string key = "Key1";
var key1Collection = vertices[key].Cast<object>().ToList();
foreach(var item in vertices.Where(x => x.Key != key ))
{
    //If you want that all the items of the collection will be in the "Key1" collection:
    if(item.Value.Cast<object>().All(x => key1Collection.Contains(x))
    {
         //Do stuff
    }

    //Or if you want that at least 1 of the items of the collection will be in the "Key1" collection:
    if(item.Value.Cast<object>().Any(x => key1Collection.Contains(x))
    {
         //Do stuff
    }
}

如果您将数据结构从ArrayList更改为List<TheTypeOfYourItems>,那么您将不再需要所有.Cast<object>

答案 3 :(得分:1)

这个怎么样:

var keys =
    vertices
        .Where(y => y.Key != "Key1")
        .Where(y => vertices["Key1"].Cast<string>().Intersect(y.Value.Cast<string>()).Any())
        .Select(x => x.Key);

或者,如果您将ArrayList更改为List<string>

var keys =
    vertices
        .Where(y => y.Key != "Key1")
        .Where(y => vertices["Key1"].Intersect(y.Value).Any())
        .Select(x => x.Key);