2012-08-03 6 views
1

아래와 같이 데이터 구조를 만들고 싶습니다. 내가 keyvaluepair 구조 가고 싶어이 일을 위해 enter image description here트리 구조를 만드는 법

. 그러나 나는 그것을 창조 할 수 없다.

public class NewStructure 
{ 
    public Dictionary<string, Dictionary<string, bool>> exportDict; 
} 

올바른 방법인가요? 그렇다면 어떻게 값을 삽입 할 수 있습니까? 삽입하면

NewStructure ns = new NewStructure(); 
ns.exportDict.Add("mainvar",Dictionary<"subvar",true>); 

이 표시됩니다. 컴파일 오류가 발생합니다. 내 마음에 아무 것도 나오지 않습니다. 어떤 제안을하시기 바랍니다.

당신은

Dictionary<string, bool> values = new Dictionary<string, bool>(); 
values.Add("subvar", true); 
ns.exportDict.Add("mainvar", values); 

에 의해 오류를 제거하지만, 아마 이런 식으로 뭔가를하려고 더 나은 you`d 얻을 수있는

답변

2

:

class MyLeaf 
{ 
    public string LeafName {get; set;} 
    public bool LeafValue {get; set;} 
} 
class MyTree 
{ 
    public string TreeName {get; set;} 
    public List<MyLeaf> Leafs = new List<MyLeaf>(); 
} 

그리고 하나를 들어 다음

+0

그는 또한'exportDict' Dictionary – NominSim

+0

@ Jleru를 초기화해야합니다. 나는 2 개 이상의 유형의 객체를 만들고 그것들을 검색하려고합니다. 귀하의 모범은 그 것에 적합합니까? – Searcher

+0

물론! MyTree의 목록을 만들고 원하는대로 채울 수 있습니다. – JleruOHeP

1

를, 당신 ' 사전에 추가하기 전에 각 사전을 초기화해야합니다.

exportDict = new Dictionary<string, Dictionary<string, bool>>(); 
Dictionary<string,bool> interiorDict = new Dictionary<string,bool>(); 
interiorDict.Add("subvar", true); 
exportDict.Add("mainvar", interiorDict); 

그러나 당신이 당신의 내부 사전은 당신이 할 수있는 하나의 키 값 쌍을해야 할 것입니다 알고있는 경우 :

exportDict = new Dictionary<string, KeyValuePair<string,bool>>(); 
exportDict.Add("mainvar", new KeyValuePair<string,bool>("subvar", true)); 
1

당신이 C# 4.0에있는 경우에이 작업을 수행 할 수있는 Dictionary<>KeyValuePair<>

귀하의 NewStructure

public class NewStructure 
{ 
    public Dictionary<string, KeyValuePair<string, bool>> exportDict = 
     new Dictionary<string, KeyValuePair<string, bool>>(); //this is still a dictionary! 
} 

될 것입니다 그리고 당신은 다음과 같이 사용할 것 :

NewStructure ns = new NewStructure(); 
ns.exportDict.Add("mainvar",new KeyValuePair<string,bool>("subvar",true)); 

사전을 사용하면 각 "리프"자체를 목록으로 만들 수 있습니다.

+0

Dictionary 개체 exportDict를'KeyValuePair' 유형으로 만들어야합니까? – Searcher

+0

아니요, exportDict는 여전히 사전입니다. 완성을 위해 초기화를 추가했습니다. – Alex

관련 문제