yo3hcv
yo3hcv

Reputation: 1669

c# XElement linq, return bool

I need to return bool type from a field that contains 1 or 0

<auto>1</auto>

Code

    public bool GetBooksAuto()
    {
        return (bool)xd.Elements("root").Elements("books").Elements("auto")
            .Select(x => x)
            .Any();
    }

Can be written in one return line or should I test strings for 1 and 0. Thank you!

Upvotes: 2

Views: 656

Answers (2)

Kram
Kram

Reputation: 526

return xd.Elements("root").Elements("books").Elements("auto")
                      .FirstOrDefault() != null;

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

If you want to check whether any of auto elements has value 1:

xd.Elements("root").Elements("books").Elements("auto")
    .Select(a => (int)a == 1) // here you get true if value is 1 and false if 0
    .Any()

You can put condition directly into Any operator:

xd.Elements("root").Elements("books").Elements("auto").Any(a => (int)a == 1)

Upvotes: 4

Related Questions