【发布时间】:2016-03-03 23:35:15
【问题描述】:
我尝试将我的 XML 文件放入带有通用列表的字典中。如何使用正确的键将正确的查询列表合并到我的字典中?代替.ToList() .ToDictionary 不行吗?
<?xml version="1.0"?>
<customers>
<cust ID="1" DeviceID="1" Name="Bob" Latitude="10" Longitude="58" Device="HW1.0"> </cust>
<cust ID="2" DeviceID="2" Name="Jack" Latitude="28" Longitude="20" Device="HW2.2"> </cust>
</customers>
//XML attribute Name is Dict Key
public class Customers
{
public int Longitude { get; set; }
public int Latitude { get; set; }
public int DeviceID { get; set; }
public string Device { get; set; }
}
class Program
{
private static Dictionary<string, List<Customers>> ReadXmlToDict(string filename)
{
// Should be Key = Xml Attribute Name Value, List of class
Dictionary<string, List<Customers>> dict = new Dictionary<string, List<Customers>>();
XDocument xdoc = XDocument.Load(filename);
var querylist = (from row in xdoc.Descendants("cust")
select new Customers()
{
//Name = (string)row.Attribute("Name"), // Wrong here should be the Dic key
DeviceID = (int)row.Attribute("DeviceID"), // list value
Longitude = (int)row.Attribute("Longitude"), // list value
Latitude = (int)row.Attribute("Latitude"), // list value
Device = (string)row.Attribute("Device") // list value
}).ToList();
return null; // null for test To.List and not Dict
}
【问题讨论】:
-
可能是这样的
(from row in xdoc.Descendants("cust")).ToDictionary(k => (string)row.Attribute("ID"), (v => select new Customers() { }).ToList());? -
谢谢,但我仍然有问题要使 linq 查询对 Dictionary
,List > 正确。语法仍然是错误的,但你的帮助给了我一个想法。我会试试的。