我嘗試將我的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