如何比较一个字典的值?

时间:2015-12-18 20:07:46

标签: c# dictionary

所以我有一个字典,其中每个字符串键可以取许多值,并且这些值被分成2个散列集(即Dictionary< string,Tuple< HashSet< string>,HashSet< string>> &GT)

现在我把字典填充为这样的

  Key        Values1        Values2
   A        Z B C D E        movie0 movie1 movie2 movie7
   B        A C D E          movie1 movie2 movie7
   C        A B D            movie1 movie7
  ...       .....            ....etc 

现在我需要的是创建一个循环遍历values2的函数,这个函数将需要2个字符串键(即A,B)如果值中存在匹配,它将增加一个计数器,所以在A的情况下和B他们都出现在movie1,movie2和movie7中,所以计数器将返回3.有没有办法实现呢?

3 个答案:

答案 0 :(得分:3)

您的数据结构看起来很奇怪。顺便说一句,如果你想这样做。

int count = dic["string1"].Item2.Intersect(dic["string2"].Item2).Count();

答案 1 :(得分:1)

valueA = dict[A];
valueB = dict[B];
var matches = valueA.Item2.Intersect(valueB.Item2).Count()

答案 2 :(得分:0)

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary < string, Tuple < HashSet < string >, HashSet < string>>> dict = new Dictionary<string,Tuple<HashSet<string>,HashSet<string>>>() {
                { "A", new Tuple<HashSet<string>, HashSet<string>>( new HashSet<string>() {"Z", "B", "C", "D", "E"}, new HashSet<string>() { "movie0",  "movie1", "movie2", "movie7"})},
                { "B", new Tuple<HashSet<string>, HashSet<string>>( new HashSet<string>() {"A", "C", "D", "E"}, new HashSet<string>() { "movie1",  "movie2", "movie7"})},
                { "C", new Tuple<HashSet<string>, HashSet<string>>( new HashSet<string>() {"A", "B", "D"}, new HashSet<string>() { "movie1",  "movie7"})}
            };

            int mathces = Matches(dict["A"].Item2, dict["B"].Item2);

        }
        static int Matches(HashSet<string> hash1, HashSet<string> hash2)
        {
            return hash1.Where(x => hash2.Contains(x)).Count();
        }
    }
}
​