Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have a dictionary for which each key can take more than one value (i.e Dictionary < string, Hashset < string > > ) And I have filled my Dictionary like this:

Key  Values

A    movie 0, movie 1, movie 2, movie 7
B    movie 0, movie 2, movie 7

And I have a counter that should count for each match there is in the values between these two keys (i.e key A, Key B), so in that case the counter should return 3, Is there a way to loop on the values of each key and every time it finds a match, it increments the counter?
Posted

Sounds fairly simple:
C#
public static int CountCommonValues<TKey, TValue>(
    this IDictionary<TKey, HashSet<TValue>> dictionary, 
    TKey keyA, TKey keyB, IEqualityComparer<TValue> comparer = null)
{
    if (dictionary == null) throw new ArgumentNullException("dictionary");
    
    HashSet<TValue> valuesA, valuesB;
    if (!dictionary.TryGetValue(keyA, out valuesA)) return 0;
    if (!dictionary.TryGetValue(keyB, out valuesB)) return 0;
    if (valuesA == null || valuesB == null) return 0;
    
    return valuesA.Intersect(valuesB, comparer).Count();
}
 
Share this answer
 
v3
Taking advantage of the fact that a HashSet has no duplicate entries: you can sum the entries they share by taking the difference of the total count of items in two Hashsets and subtract the number of items in their 'Union:
C#
HashSet<string> hs1 = new HashSet<string>
{
    "m0","m1","m2","m7"
};

HashSet<string> hs2 = new HashSet<string>
{
    "m0","m2","m7"
};

private int GetSharedMovieCount(HashSet<string> h1, HashSet<string> h2)
{
    return h1.Count + h2.Count - (h1.Union(h2).Count());
}

// test in some Method or EventHandler
Dictionary<string, HashSet<string>> movies = new Dictionary<string, HashSet<string>>
{
     {"movie1", hs1},
     {"movie2", hs2}
};

int cnt = GetSharedMovieCount(movies["movie1"], movies["movie2"]); // => 3
 
Share this answer
 
v3
Comments
Richard Deeming 4-Jan-16 8:34am    
Taking the intersection is easier! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900