我尝试将我的XML文件放入具有通用列表的字典中。我如何使用正确的键将正确的查询列表合并到我的字典中?而不是.ToList()
.ToDictionary
是不可能的?字典<字符串,列表<ClassObj>> LINQ到XML查询
<?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
}
也许是这样的'(从xdoc.Descendants行(“卡斯特”))ToDictionary( k =>(string)row.Attribute(“ID”),(v => select new Customers(){})。ToList());'? – Tim
谢谢,但我仍然有问题,使linq查询正确的字典,名单>。语法仍然是错误的,但你的帮助给了我一个想法。我会尝试。 –
Shazter