2016-10-26 1 views
0

나는 다음과 같이 사전 [mapData]이 있고 키가 [Dictionary< string, DateTime >][mapData]에 존재입니다 확인했지만 작동하지 않았다 : 작동키 자체가 사전 인 경우 사전에 키가 있는지 확인하는 방법 (C#)?

 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

에서오고있다 "는 작동하지 않았다"우리에게 당신이 본 것에 대해 아무것도 말해주지 않습니다. 사전을 사용하는 것이 나쁜 선택 인 것처럼 들리지만 확실히 키의 아주 이상한 선택입니다. 학생의 이름과 생일을 제외하고이 사전에 무엇을 넣기를 기대합니까? –

답변

2

키 내용이 아닌 개체 참조를 기반으로 키를 찾으려고하기 때문입니다. dictionnary 키는 Key + 값 (string + DateTime) 참조의 조합입니다.

당신이 다시 작성하지 않는 한

이 실 거예요 작업과

var objectA = new ObjectA(); 
var objectB = new ObjectA(); 

objectA != objectBIEqualityComparer. 당신은 등호를 rewritte하지 않는.

편집

이 샘플은 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. 
2

당신은 거기에 가고 싶지 않습니다. 복잡한 객체는 사전의 키가 아닙니다. 사전을 값으로 옮기고 더 나무와 같은 구조를 만들 것을 제안합니다.

이 작업을 수행 할 수있는 가능성이 있지만 위에서 설명한 이유로 사전에 키를 다른 사전과 비교하는 사용자 지정 IEqualityComparer을 구현하는 것이 좋습니다.

관련 문제