Linq-XML总是那么混乱吗?

Fin*_*las 6 .net c# linq linq-to-xml

var subset = from item in document.Descendants("Id")
             where item.Value == itemId.ToString()
             select new PurchaseItem() {
                 Id = int.Parse(item.Parent.Element("Id").Value),
                 Name = item.Parent.Element("Name").Value,
                 Description = item.Parent.Element("Description").Value,
                 Price = int.Parse(item.Parent.Element("Price").Value)
             };
Run Code Online (Sandbox Code Playgroud)

XML的结构如下:

<Items>
    <Item>
        <Id></Id>
        <Name></Name>
        <Description></Description>
        <Price></Price>
    </Item>
</Items>
Run Code Online (Sandbox Code Playgroud)

Id和价格都是整数值.名称和描述是字符串.

我发现我用过Linq to XML的东西很棒,这只是一个片段.但是,另一方面,我感觉它应该或可能更清洁.在这个片段中,转换似乎是最明显的问题.

有什么建议?

Jon*_*eet 13

实际上,施法比投出更好的IMO int.Parse.这是我写你的查询的方式:

string id = itemId.ToString(); // We don't need to convert it each time!

var subset = from item in document.Descendants("Id")
             where item.Value == id
             let parent = item.Parent
             select new PurchaseItem
             {
                 Id = (int) parent.Element("Id"),
                 Name = (string) parent.Element("Name"),
                 Description = (string) parent.Element("Description"),
                 Price = (int) parent.Element("Price")
             };
Run Code Online (Sandbox Code Playgroud)

  • XElement为公共数据类型定义自定义转换运算符.因此,当您转换XElement时,您实际上正在调用其中一个运算符,它会读取值并将其转换.你不要显式调用`.Value`有两个原因:一,Value是一个字符串,那些自定义运算符是在XElement上定义的,而不是字符串.二,抛出恰好为null的XElement将返回null,而在空XElement上调用.Value将导致异常.过滤时很有用. (3认同)