当密钥本身是字典(C#)时,如何检查字典中是否存在密钥?

时间:2016-10-26 06:33:31

标签: c# dictionary

我有一个字典[mapData],如下所示,检查密钥是[Dictionary< string, DateTime >]存在[mapData],但它不起作用:

        var mapData = new Dictionary<Dictionary<string, DateTime>, List<Student>>();

        foreach (var st in listStudent)
        {
            // Create Key
            var dicKey = new Dictionary<string, DateTime>();
            dicKey.Add(st.Name, st.Birthday);

            // Get mapData
            if (!mapData.ContainsKey(dicKey))       // ===> Can not check key exists
            {
                mapData.Add(dicKey, new List<Student>());
            }
            mapData[dicKey].Add(st);
        }

我尝试使用扩展方法,如下所示,但也无法正常工作:

        public static bool Contains<Tkey>(this Dictionary<Tkey, List<Student>> dic, Tkey key)
        {
            if (dic.ContainsKey(key))
                return true;
            return false;
        }

任何有关这些的提示都会有很大帮助。提前谢谢。

2 个答案:

答案 0 :(得分:2)

你不想去那里。复杂对象不是字典中的键。我建议将字典移动到值,并创建一个更像树的结构。

有一种方法可以让这个工作,但我会建议反对它出于上述原因:自定义IEqualityComparer的实现,它将字典中的键与另一个字典进行比较。

答案 1 :(得分:2)

这是因为您尝试根据对象引用而不是关键内容查找密钥。 您的词典键是Key + value (string + DateTime)引用的组合。

除非你重写并IEqualityComparer.

,否则这不会奏效
var objectA = new ObjectA();
var objectB = new ObjectA();

objectA != objectB除非你重写等于。

<强> 修改

此示例来自MSDN https://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx

using System;
using System.Collections.Generic;

class Example
{
   static void Main()
   {
      BoxEqualityComparer boxEqC = new BoxEqualityComparer();

      var boxes = new Dictionary<Box, string>(boxEqC);

      var redBox = new Box(4, 3, 4);
      AddBox(boxes, redBox, "red");

      var blueBox = new Box(4, 3, 4);
      AddBox(boxes, blueBox, "blue");

      var greenBox = new Box(3, 4, 3);
      AddBox(boxes, greenBox, "green");
      Console.WriteLine();

      Console.WriteLine("The dictionary contains {0} Box objects.",
                        boxes.Count);
   }

   private static void AddBox(Dictionary<Box, String> dict, Box box, String name)
   {
      try {
         dict.Add(box, name);
      }
      catch (ArgumentException e) {
         Console.WriteLine("Unable to add {0}: {1}", box, e.Message);
      }
   }
}

public class Box
{
    public Box(int h,  int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }

    public int Height { get; set; }
    public int Length { get; set; }
    public int Width { get; set; }

    public override String ToString()
    {
       return String.Format("({0}, {1}, {2})", Height, Length, Width);
    }
}


class BoxEqualityComparer : IEqualityComparer<Box>
{
    public bool Equals(Box b1, Box b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null | b2 == null)
           return false;
        else if(b1.Height == b2.Height && b1.Length == b2.Length
                            && b1.Width == b2.Width)
            return true;
        else
            return false;
    }

    public int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }
}
// The example displays the following output:
//    Unable to add (4, 3, 4): An item with the same key has already been added.
//
//    The dictionary contains 2 Box objects.
相关问题