简体   繁体   English

我可以更好地将此LINQ重写为XML吗?

[英]Can I rewrite this LINQ to XML better?

I'm just learning LINQ and in particular LINQ to XML, and I've written up a query that works but I'm wondering if I'm doing it a bit round-a-bout. 我只是在学习LINQ,尤其是LINQ to XML,我编写了一个有效的查询,但是我想知道我是否正在做一番尝试。 Can the code be improved? 可以改进代码吗?

I have an XDocument: 我有一个XDocument:

<SomeDocument>
    <Prop1> val1 </Prop1>
    <Prop2> val2 </Prop2>
    <Prop3> val3 </Prop3>
</SomeDocument>

But Prop1, Prop2, and Prop3 may not be there. 但是Prop1,Prop2和Prop3可能不存在。 There may be other XDocuments which I'll be parsing with the same code, that have different properties altogether. 可能还有其他我将用相同代码解析的XDocument,它们具有完全不同的属性。 But I'm only interested in the XDocument if it has Prop1 or both Prop1 and Prop2. 但是我只对XDocument具有Prop1或Prop1和Prop2感兴趣。

var query = from n in xml.Elements()
                    where n.Name == "Prop1" || n.Name == "Prop2"
                    select new {n.Name, n.Value};

string prop1 = null;
string prop2 = null;

foreach (var n in query)
{
    if (n.Name == "Prop1") prop1 = n.Value;
    if (n.Name == "Prop2") prop2 = n.Value;
}

if (string.IsNullOrEmpty(prop1)) { //error } 
if (string.IsNullOrEmpty(prop2)) { DoMethod1(prop1); }
else { DoMethod2(prop1, prop2); }

The code after the query seems way too long to me, though I'm not sure if there's a better way of doing what I'm trying to do. 查询后的代码对我来说似乎太长了,尽管我不确定是否有更好的方法来做我想做的事情。 Find 1 or 2 explicit Nodes, and call relevant methods depending on what (if any) nodes are found. 查找1或2个显式节点,并根据找到的节点(如果有)调用相关方法。

personally I use: 我个人使用:

        var element = xml.Element("prop1");
        if (element!= null)
        {
            //The element exists, now do things on it!
            if(string.IsNullOrEmpty(element.Value)) {DoMe(element.Value);}
        }

if you have named properties (elements) that you know, you can just name them and it will be returned. 如果您已经知道了命名的属性(元素),则只需命名它们即可将其返回。 This also saves extra looping (in your code at least) 这也节省了额外的循环(至少在您的代码中)

You could probably eliminate the middle part if you break out the results into a lookup, ie: 如果将结果分解为一个查找,则可以消除中间部分,即:

string[] propNames = new[] { "Prop1", "Prop2" };
var props = (from n in xml.Elements()
             where propNames.Contains(n.Name)
             select new { n.Name, n.Value })
            .ToLookup(e => e.Name, e => e.Value);

if (props.Contains("Prop1")) { ... }
if (props.Contains("Prop2")) { ... }
// etc.

How much of an improvement this is depends on what else you're doing with this information, but it's a little cleaner at least. 这有多大的改进取决于您对这些信息所做的其他事情,但是至少可以使它更清洁一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM