2012-11-19 2 views
3

Linq를 사용하여 Dictionary (또는 더 나은 것은 ConcurrentDictionary)을 어떻게 만듭니 까? 예를 들어Linq를 사용하여 사전 만들기

, 나는 다음과 같은 XML

<students> 
    <student name="fred" address="home" avg="70" /> 
    <student name="wilma" address="home, HM" avg="88" /> 
    . 
    . (more <student> blocks) 
    . 
</students> 

XDocument doc;에로드 웁니다 원이있는 경우 키가 이름이고 Info 몇 가지 클래스 개최 주소 및 평균 곳에는 ConcurrentDictionary<string, Info> (. Info 채우기 것은 아니다 지금 내 관심사), 어떻게해야합니까? 이 같은

+1

은 "LINQ를 사용하여"요구 사항 또는 추세입니까? – Vlad

+1

가능한 복제본 : http://stackoverflow.com/questions/1710193/converting-an-xml-document-to-a-dictionary – Christian

+2

@Vlad 추세입니다. – baruch

답변

9
XDocument xDoc = XDocument.Parse(xml); 
var dict = xDoc.Descendants("student") 
       .ToDictionary(x => x.Attribute("name").Value, 
           x => new Info{ 
            Addr=x.Attribute("address").Value, 
            Avg = x.Attribute("avg").Value }); 


var cDict = new ConcurrentDictionary<string, Info>(dict); 
+0

예, 보았습니다. 문서를 다시 검토했습니다. – Vlad

+0

'ConcurrentDictionary'가 필수이면'.ToDictionary'를 건너 뛰고'foreach' 루프의 빈'ConcurrentDictionary'에 시퀀스를 직접로드하는 것이 더 나을 것입니다. 이렇게하면 버려지는'Dictionary' ('dict')을 만드는 것을 피할 수 있습니다. – spender

3

뭔가 할 것입니다 :

var dict = xml.Descendants("student") 
       .ToDictionary(r => (string)r.Attribute("name").Value, r => CreateInfo(r)); 

이 그냥 보통 Dictionary 생산; ConcurrentDictionaryfrom the usual Dictionary을 생성 할 수 있습니다.


편집 : 덕분에이 몰래 위해 @spender하기 AttributeElement을 변경했습니다. @Jaroslaw 덕분에 "학생"-> "학생".

+0

테스트 해 보셨습니까? – jwaliszko

+0

@Jaroslaw : 아니, 실제로 - 문제가 있습니까? 그렇다면 답을 개선하는 데 도움을 줄 수 있습니다 (또는 자신 만의 답을 줄 수 있습니다). – Vlad

+0

예 실수가 있습니다.이 문제를 해결하십시오. – jwaliszko

관련 문제