2011-11-12 4 views
5

하나의 목록에 2 개의 값을 저장해야하므로 모든 위치와 내 컨트롤이 하나의 목록에 포함됩니다. 사전을 사용하고 있었지만 단 하나의 매핑 만 있다는 것을 알았습니다. 2 차원 배열을 제외한 모든 권장 사항이 있습니까?양방향 매핑 목록

+0

하나의 Collection에 2 가지 다른 유형을 저장하고 싶습니까? –

+0

예, 정확하게하고 싶습니다! –

답변

6

당신이 (당신이 어쨌든 2 차원 배열을 얻을 것) 역 매핑을위한 선형 검색 성능에 대해 신경 쓰지 않는 경우가 양방향 매핑 쉽게 충분한 사전을 사용할 수 있습니다

var dictionary = new Dictionary<string, int>(); 
// Fill it up... 
int forwardMapResult = dictionary["SomeKey"]; 
string reverseMapResult = dictionary.Where(kvp => kvp.Value == 5).First().Key; 

조회 속도가 문제가되는 경우 정방향 조회와 역순으로 두 개의 사전을 유지 관리해야합니다. 또는 SQLite와 같은 메모리 내에서 인덱싱 가능한 데이터베이스를 사용하십시오.

7

이 도움이 될 수 있습니다 : 왼쪽과 오른쪽이 같은 종류가 ... 즉, 그것은 작동하지 않는 경우에 이것은 당신이 시도를 잘하면 문제가있는

public class BiDirectionalDictionary<L, R> 
{ 
    private readonly Dictionary<L, R> leftToRight = new Dictionary<L, R>(); 
    private readonly Dictionary<R, L> rightToLeft = new Dictionary<R, L>(); 
    public void Add(L leftSide, R rightSide) 
    { 
     if (leftToRight.ContainsKey(leftSide) || 
      rightToLeft.ContainsKey(rightSide)) 
      throw new DuplicateNameException(); 
     leftToRight.Add(leftSide, rightSide); 
     rightToLeft.Add(rightSide, leftSide); 
    } 
    public L this[R rightSideKey] 
    { get { return rightToLeft[rightSideKey]; } } 
    public R this[L leftSideKey] 
    { get { return leftToRight[leftSideKey]; } } 
    public bool ContainsKey(L leftSideKey) 
    { return leftToRight.ContainsKey(leftSideKey); } 
    public bool ContainsKey(R rightSideKey) 
    { return rightToLeft.ContainsKey(rightSideKey); } 
} 
[Serializable] 
public class DuplicateNameException : SystemException 
{ 
    protected DuplicateNameException(
      SerializationInfo info, StreamingContext context); 
    public DuplicateNameException(); 
    public DuplicateNameException(string s); 
    public DuplicateNameException(string message, 
      Exception innerException); 
} 

var myBiDireDict = new BiDirectionalDictionary<DateTime, DateTime>(); 
+0

L & R이 같은 유형이 아니며 항상 1 대 1의 관계가 있다고 가정하면 매우 좋습니다. –