用于创建字典的Linq查询
我需要简单的linq查询,这将创建字典 我有Xml,其中包含可以购买某些产品的客户列表 对于每个客户,只能免费提供一种产品 下面是我的示例Xml 我用板条箱装了一个看起来像用于创建字典的Linq查询,linq,linq-to-xml,Linq,Linq To Xml,我需要简单的linq查询,这将创建字典 我有Xml,其中包含可以购买某些产品的客户列表 对于每个客户,只能免费提供一种产品 下面是我的示例Xml 我用板条箱装了一个看起来像 Public Class CustomerFreeItem { public string CustomerID public string FreeproductName public string ActualPrice } <customers> <customer id="1"&g
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>
公共类CustomerFreeItem
{
公共字符串自定义ID
公共字符串FreeproductName
公共字符串实际价格
}
从上面的Xml中,我想要一个以客户ID为键、值为FreeProduct(CustomerFreeItem对象)的字典
请建议
谢谢,
Salmon.因此不清楚您使用的是哪种语言(类声明在C#和VB中都无效),这里是C#solution
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);
我假设每个客户都有一个免费的产品。制作一个具有这种布局的词典,然后使用,您将看到所需的格式。然后你可以颠倒这个过程,你的字典就会被填满。你自己的方法在哪里?是
vb.net
还是c#
?我假设它是您的类声明中的vb
。也是每个客户都有免费的产品吗?是否只有一种免费产品,或者一个客户可以有更多的免费产品?
public class CustomerFreeItem
{
public int CustomerID { get; set; }
public string FreeproductName { get; set; }
public int ActualPrice { get; set; }
}