Only get the value if a condition is true

Posted by Autolycus on Stack Overflow See other posts from Stack Overflow or by Autolycus
Published on 2011-11-30T01:31:24Z Indexed on 2011/11/30 1:50 UTC
Read the original article Hit count: 134

Filed under:
|

I am checking to see if element1, element 2 or element 3 exists and then add them to finalData if they exist. However if one of those dont exist or are not true then I just want to add the elements whose bool value is true! Below is my code

bool hasElement1 = (

                from Playlist in loaded.Descendants("Node")
                select Playlist.Descendants("Element1").Any()
                ).Single();

bool hasElement2 = (

                from Playlist in loaded.Descendants("Node")
                select Playlist.Descendants("Element2").Any()
                ).Single();

bool hasElement3 = (

                from Playlist in loaded.Descendants("Node")
                select Playlist.Descendants("Element2").Any()
                ).Single();

var finalData = from x in loaded.Descendants("Node")

                            select new
                            {

                                Element1 = x.Descendants("Element1").First().Value,
                                Element2 = x.Descendants("Element2").First().Value,
                Element3 = x.Descendants("Element3").First().Value,

                            };

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ