Srini Srini - 2 months ago 14
C# Question

C# Determine if Dictionary Contains All of a Set of Values

I have the following dictionary :

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


Now I'm trying to figure out is how to check for each of the dictionary's other keys (like
"Key2"
or
"Key3"
) if their values contain one or all of the values from
"Key1"
's values (
ArrayList
), but its not working. This might be very straight forward, but I could not get it

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

Answer

The problem is that you are passing the wrong thing to the Contains. Contains is supposed to receive an item to look for in the collection but you are passing an entire collection. Because you are using ArrayList, where the items are stored as object you are not receiving a compile time error but it just doesn't work (and the items are compared using object's compare which is to check references.

You can use Linq to do it this way:

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

If you change your data structure from ArrayList to List<TheTypeOfYourItems> then you won't need all the .Cast<object>