【问题标题】:linq AncestorsAndSelf with null argument带有空参数的 linq AncestorsAndSelf
【发布时间】:2015-04-02 19:21:58
【问题描述】:

如何将这两个 linq 查询重写为一个? .AncestorsAndSelf 不支持 null 作为元素名称。

        if (ancestorElementName == null)
        {
            ancestorElements =
                currentElement
                .AncestorsAndSelf()
                .Select(
                    .
                    .
                    .
                    );
        }
        else
        {
            ancestorElements =
                currentElement
                .AncestorsAndSelf(ancestorElementName)
                .Select(
                    .
                    .
                    .
                    );
        }

【问题讨论】:

  • 为了澄清你想在指定元素不为空时使用linq来选择它?

标签: c# linq linq-to-xml


【解决方案1】:

如何添加一个处理此方法选择的扩展方法。这将允许您保持查询的其余部分相同。

如:

public static class MyLinqToXmlExtensions
{
    public static IEnumerable<XElement> ForAncestorsAndSelf(this XElement e, XName name)
    {
        return name == null ? e.AncestorsAndSelf() : e.AncestorsAndSelf(name);
    }
};

然后你可以用作

ancestorElements = currentElement
    .ForAncestorsAndSelf(ancestorElementName)
    .Select(
            .
            .
            .
            );

【讨论】:

    【解决方案2】:

    编写您自己的扩展程序,如下所示:

    public static class MyExtensions
    {
         public static IEnumerable<XElement> MyAncestorsAndSelf(this IEnumerable<XElement> source, XName name)
         {
             if(name == null)
             {
                 return source.AncestorsAndSelf();
             }
    
             return source.AncestorsAndSelf(name);
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      相关资源
      最近更新 更多