Search code examples
c#linqlambdaxelement

Avoid Repeating Oneself When Doing A Select From IEnumerable


I have an IEumerable<XElement> called foo.

I have this code

foo.Select(x => new
        {
            bars = x.Descendants(namespace + "bar") != null 
                ? x.Descendants(namespace + "bar").Select(z => z.Value).ToArray() 
                : new string[0]
        })
        .ToArray();

How can I write this a little neater? I really don't want to repeat this part

x.Descendants(namespace + "bar")

Solution

  • Using an additional Select:

    foo.Select(x => x.Descendants(namespace + "bar"))
       .Select(x => new
                {
                    bars = x != null ? x.Select(z => z.Value).ToArray() : new string[0]
                })
                .ToArray();
    

    Or:

    foo.Select(x =>
                   {
                       var elements = x.Descendants(namespace + "bar");
                       return new
                       {
                          bars = elements != null ? elements.Select(z => z.Value).ToArray() : new string[0]
                       }
                    })
                .ToArray();
    

    BTW, I don't think Descendants will return null.You should probably check whether there are any elements using Any method.

     bars = x.Any() ? x.Select(z => z.Value).ToArray() : new string[0]