2016-08-18 108 views
1

我有這個XML結構,我需要計算非空工作和家庭元素,groupby Country屬性,然後orderby國家屬性。C#Linq XML GroupBy OrderBy get count

Something like Dictionary>,但我用linq表達式失敗。目前,該列表僅被過濾,groupby和orderby。缺少的部分是計數非空工和家庭元素。 是否有可能在查詢中做到這一點或在查詢列表後應該使用?

XMLFILE

<?xml version="1.0" encoding="utf-8"?> 
<Root> 
    <Region ID="NA"> 
     <Name>QWERTZ</Name> 
     <Country ID="1"> 
      <Facility Name="1"> 
       <Department Name="1"> 
        <Member Name="1"> 
         <Home>555-666</Home> 
         <Work>111-666</Work> 
        </Member> 
       </Department> 
      </Facility> 
     </Country>  
    </Region> 
     <Region ID="CHINA"> 
     <Name>ASDF</Name> 
     <Country ID="2"> 
      <Facility Name="2"> 
       <Department Name="2"> 
        <Member Name="2"> 
         <Home>111-222</Home> 
         <Work>111-222</Work> 
        </Member> 
       </Department> 
      </Facility> 
     </Country>  
    </Region> 
    <Region ID="EU"> 
     <Name>ASDF</Name> 
     <Country ID="3"> 
      <Facility Name="3"> 
       <Department Name="1"> 
        <Member Name="1"> 
         <Home>111-222</Home> 
         <Work></Work> 
        </Member> 
       </Department> 
      </Facility> 
     </Country>  
    </Region> 
</Root> 

方法

public static List<IGrouping<string,XElement>> getgrouped(string filename) 
{ 
    XDocument xml = XDocument.Load(filename); 

    return xml.Root 
     .Descendants("Country") 
     .GroupBy(x => (string)x.Attribute("ID").Value) 
     .OrderBy(g => g.Key) 
     .ToList(); 
} 

回答

2

對於每一個項目我與該國的id和非空的後代WorkHome元素數量的對象後代。然後我GroupBy和總結計數器。

xml.Root.Descendants("Country") 
    .Select(element => new 
    { 
     Id = (string) element.Attribute("ID").Value, 
     NonEmptyWork = element.Descendants("Work") 
           .Count(w => !string.IsNullOrEmpty(w.Value)), 
     NonEmptyHome = element.Descendants("Home") 
           .Count(w => !string.IsNullOrEmpty(w.Value)) 
    }) 
    .GroupBy(item => item.Id) 
    .Select(g => new 
    { 
     Id = g.Key, 
     NonEmptyWorkAmount = g.Sum(item => item.NonEmptyWork), 
     NonEmptyHomeAmount = g.Sum(item => item.NonEmptyHome) 
    }) 
    .OrderBy(item => item.Id) 
    .ToList(); 

以將其輸出作爲字典代替ToList:!

// Dictionary<string, YourType> 
    .ToDictionary(key => key.Id, value => value); 
+0

編號=(字符串)x.Attribute( 「ID」)值X爲未知的,.Count之間(W =>串.IsNullOrEmpty(w.InnerText))w.innertext也是未知的,但你給了理解的正確方向。 – Shazter

+0

謝謝我解決了你的幫助,看到答案 – Shazter

+0

作品完美和upvoted – Shazter