[英]LINQ to XML Newbie Question
有没有更好的方法来做这种事情:
var filter = new CashFilters();
var element = XElement.Parse(request.OuterXml);
var productId = element.Elements("ProductId").Select(el => el);
if (productId.Count() == 1)
filter.ProductId = Convert.ToInt32(productId.Single().Value);
好吧, Select(el => el)
开始对您没有任何好处。
我建议您使用SingleOrDefault
:
var productId = element.Elements("ProductId").SingleOrDefault();
if (productId != null)
filter.ProductId = Convert.ToInt32(productId.Value);
请注意,这处理了没有 ProductId元素的情况,但是如果存在多个元素,则将引发异常。 如果这确实是有效的情况,那么您当前的代码(没有多余的Select
调用)是合理的。
编辑:您可以通过以下方法摆脱这种情况:
var productId = element.Elements("ProductId")
.Select(elt => elt.Value)
.SingleOrDefault();
filter.ProductId = Convert.ToInt32(productId ?? filter.ProductId.ToString());
但这很可怕;)
基本上,您已有条件-仅在指定ProductId
的情况下才需要设置它。 “ if”语句是有条件地执行代码的普遍接受的方法:)
还有其他选择:
filter.ProductId = productId == null
? filter.ProductId
: int.Parse(productId);
如果您不介意将filter.ProductId
设置为0(如果未指定ID),则可以使用:
filter.ProductId = Convert.ToInt32(element.Elements("ProductId")
.Select(elt => elt.Value)
.SingleOrDefault());
(由于在传递null参数时Convert.ToInt32
返回0的方式。)
您真的需要在Linq to Xml中执行此操作吗? Xml DOM方法对我来说似乎更合理。
您是否考虑过纯Xml方法?
XmlDocument doc = new XmlDocument();
doc.LoadXml(request.OuterXml);
var node = doc.SelectSingleNode("//ProductId[1]");
if (node != null)
filter.ProductId = Convert.ToInt32(node.InnerText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.