【问题标题】:How to compare values of one dictionary?如何比较一本字典的值?
【发布时间】:2015-12-18 20:07:46
【问题描述】:

所以我有一个字典,每个字符串键可以取多个值,这些值分为2个哈希集(即字典,哈希集>>)

现在我的字典是这样填的

 关键值1 值2
   A Z B C D E 电影0 电影1 电影2 电影7
   B A C D E 电影1 电影2 电影7
   C A B D 电影1 电影7
  ………………等 

现在我需要创建一个循环遍历 values2 的函数,该函数将采用 2 个字符串键(即 A、B)如果值匹配,它将增加一个计数器,因此在 A 的情况下和 B 他们都出现在电影 1、电影 2 和电影 7 中,所以计数器会返回 3。有没有办法做到这一点?

【问题讨论】:

  • 你需要接受面向对象的编程。将所有内容分解为类并使用组合。你在折磨字典和字符串类。
  • 好吧,我打算为一个字符串和一个哈希集分别制作 2 个字典,但我认为这很糟糕......这是一个更好的开始吗?
  • 您会发现您的程序几乎可以做任何事情。您可以这样做,但它需要权衡取舍,例如可读性、可维护性或可扩展性。像@roryap 一样,我建议您稍微分解一下您的数据结构,或者澄清为什么您需要以这种方式循环来做到这一点。对于简单的解决方案而言,您的数据似乎过于复杂。
  • 好吧,我的数据结构应该是一个图形,而我填写字典的方式是从文件中读取...我的应用程序应该用 3 个不同的函数来演示小世界问题,第一个是计算 2 个节点(即 A/B)之间的分离程度,我实际上能够通过使用 BFS 并仅制作类似于这样的数据结构(即 Dictionary >) 所以电影并不是那么重要,但现在我需要计算每个 2 个节点出现的电影数量,所以我在考虑 a-
  • 电影和节点及其邻居之间的连接方式,所以是的,这就是我想到元组的原因,这就是为什么我需要以这种方式循环......对不起,我希望这能回答你的问题为什么我需要这样循环。

标签: c# dictionary


【解决方案1】:

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

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

【讨论】:

  • 谢谢你,它成功了,但我想我得想一个更好的方法来表达我的数据结构!
【解决方案2】:
valueA = dict[A];
valueB = dict[B];
var matches = valueA.Item2.Intersect(valueB.Item2).Count()

【讨论】:

    【解决方案3】:

    试试这个

    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();
            }
        }
    }
    ​
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多