是的LINQ XML总是这么乱? [英] Is Linq-XML always so messy?

查看:160
本文介绍了是的LINQ 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)
             };

在XML的结构如下:

The structure of the XML is as follows:

<Items>
    <Item>
        <Id></Id>
        <Name></Name>
        <Description></Description>
        <Price></Price>
    </Item>
</Items>

ID和价格都是整数值。名称和描述都是字符串。

Id, and price are both integer values. Name and description are strings.

我发现的LINQ to XML 伟大的东西我已经使用了,这仅仅是一个片段。但是,在另一方面,我得到的感觉它应该或可能是更清洁。铸造似乎在这个片段中最明显的问题。

I've found Linq to XML great for what I've used it for, this is just a snippet. But, on the other hand I get the feeling it should or could be cleaner. The casting seems the most obvious issue in this snippet.

任何意见?

推荐答案

其实倒不如IMO投,而不是叫 int.Parse 。下面是我会写你的查询:

Actually it would be better IMO to cast than to call int.Parse. Here's how I would write your query:

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")
             };

这篇关于是的LINQ XML总是这么乱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆