判断字典是否包含一组值的全部

本文关键字:全部 包含一 字典 是否 判断 | 更新日期: 2023-09-27 18:12:20

我有以下字典:

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

判断字典是否包含一组值的全部

问题是您正在传递错误的东西给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>

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

您不能将集合传递给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
            }
        }

这个怎么样:

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