【问题标题】:Assign multiple strings to unique string C# MultiMap, Dictionary or another method?将多个字符串分配给唯一的字符串 C# MultiMap、Dictionary 或其他方法?
【发布时间】:2014-08-22 12:16:29
【问题描述】:

我目前的问题是我目前有两个字符串,其中包含可用于将它们相互匹配的数据。该数据是IP源地址和IP目的地址。 我要做的是将 IP 源与其所有目标地址匹配。我目前的代码如下所示。

 var xmlDoc2 = new XmlDocument();
 xmlDoc2.Load(textBox1.Text);
 HashSet<string> hs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
 var node = xmlDoc2.SelectNodes("pdml/packet/proto[@name='ip']/@showname");

   foreach (XmlAttribute attribute1 in node)
   {
     string ip = attribute1.Value;
     var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
     if (hs.Contains(src))
     {
      string ipsrc = src;
      string ipdst = dst;
      listBoxDST.Items.Add(ipdst);
     }
     else
     {
      hs.Add(src);
      string ipdst = dst;
      string ipsrc = src;
      listBoxSRC.Items.Add(ipsrc);
      listBoxDST.Items.Add(ipdst);
      }
   }

我看过 MultiMapping,但它只在 C++ 中使用(再次,如果我错了,请纠正我)。

我还查看了字典,最好将 ipdst 存储为列表并将其添加到密钥(ipsrc)中。由于哈希集的 if 语句,我似乎无法弄清楚如何使其以这种方式工作。 (上面的代码没有失败的字典实现。

如果我在 Access 中创建一个数据库用作存储会更好吗?或者有什么方法可以让我拥有一个包含目标地址列表的唯一源地址?

谢谢, 汤姆

【问题讨论】:

    标签: c# string dictionary


    【解决方案1】:

    我实现了您的代码的Dictionary 版本。

    试试这个:

    var xmlDoc2 = new XmlDocument();
    xmlDoc2.Load(textBox1.Text);
    Dictionary<string, List<string>> hs = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
    
    var node = xmlDoc2.SelectNodes("pdml/packet/proto[@name='ip']/@showname");
    
    foreach (XmlAttribute attribute1 in node)
    {
        string ip = attribute1.Value;
        var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
    
        List<string> l;
        if (!hs.TryGetValue(src, out l))
        {
            hs[src] = l = new List<string>();
        }
    
        l.Add(dst);
    }
    

    它使用TryGetValue 来检查该字典中是否已经存在一个键。如果 ip 地址不存在,它会添加一个列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2019-10-13
      • 1970-01-01
      • 2012-02-19
      相关资源
      最近更新 更多