我正在检查是否存在element1,element 2或element 3,然后将它们添加到finalData(如果它们存在)。然而 如果其中一个不存在或不存在,那么我只想添加其bool值为true的元素!以下是我的代码
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,
};
答案 0 :(得分:2)
在检索元素之前,您无需检查元素是否存在。试试这个:
var finalData = from x in loaded.Descendants("Node")
select new
{
Element1 = (string)x.Descendants("Element1").FirstOrDefault(),
Element2 = (string)x.Descendants("Element2").FirstOrDefault(),
Element3 = (string)x.Descendants("Element3").FirstOrDefault(),
};