2012-11-10 41 views
-2

我需要簡單的LINQ查詢,這將創造字典 我對XML其中包含可以作爲免費 以下的客戶,誰可以買一些產品 爲每一位客戶只有一個產品的名單是我的示例XML 我已經裝箱的一類,看起來像LINQ查詢創建詞典

Public Class CustomerFreeItem 
{ 
    public string CustomerID 
    public string FreeproductName 
    public string ActualPrice 
} 

<customers> 
    <customer id="1"> 
    <product name="book" free="false" actualPrice="10"/> 
    <product name="pen" free="true" actualPrice="10"/> 
    <product name="scale" free="false" actualPrice="10"/> 
    </customer> 
    <customer id="2"> 
    <product name="book" free="true" actualPrice="10"/> 
    <product name="pen" free="false" actualPrice="10"/> 
    <product name="scale" free="false" actualPrice="10"/> 
    </customer> 
    <customer id="3"> 
    <product name="book" free="false" actualPrice="10"/> 
    <product name="pen" free="false" actualPrice="10"/> 
    <product name="scale" free="true" actualPrice="10"/> 
    </customer> 
</customers> 

弗羅姆以上的XML我想有一個字典客戶ID作爲鍵和值FreeProduct(CustomerFreeItem對象)

請建議

謝謝, 鮭魚。

+0

你自己的方法在哪裏? – KroaX

+0

它是'vb.net'還是'c#'?我認爲它是你的類聲明中的'vb'。每個客戶都有免費產品嗎?是否只有一種免費產品,或者一個客戶可能有更多免費產品? –

回答

1

因此目前還不清楚您所使用的語言(類聲明是雙方在C#和VB無效)這裏是C#soulution

XDocument xdoc = XDocument.Load(path_to_xml_file); 
var query = from c in xdoc.Descendants("customer") 
      let freeProduct = c.Elements("product") 
           .Where(p => (bool)p.Attribute("free")) 
           .Single()       
      select new CustomerFreeItem() 
      { 
       CustomerID = (int)c.Attribute("id"), 
       FreeproductName = (string)freeProduct.Attribute("name"), 
       ActualPrice = (int)freeProduct.Attribute("actualPrice") 
      }; 

Dictionary<int, CustomerFreeItem> dictionary = 
    query.ToDictionary(x => x.CustomerID); 

我用下面的類聲明:

public class CustomerFreeItem 
{ 
    public int CustomerID { get; set; } 
    public string FreeproductName { get; set; } 
    public int ActualPrice { get; set; } 
} 

而且我認爲每個客戶都有一個免費產品。

0

使用佈局製作字典並使用XmlSerializer,您將看到所需的格式。然後你可以逆轉這個過程,你的詞典就會被填滿。