2012-11-10 138 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,您将看到所需的格式。然后你可以逆转这个过程,你的词典就会被填满。