我有这个,我可以选择我想要的,当周期是2。但如果周期2不存在,我想选择周期为3的地方。如何?
return document.Descendants("time")
.Where(node => (string)node.Attribute("period") == "2")
.Take(5)
.Select(status => WeatherFactory.Create(status, city, pos))
.ToList();
你就不能把Where改成:
.Where(node => (string)node.Attribute("period") == "2" || (string)node.Attribute("period") == "3")
?
如果首先选择period == 2的所有子节点,检查它是否包含任何结果,如果不选择period == 3的所有子节点:
var timeDescendants = document.Descendants("time")
.Where(node => (string)node.Attribute("period") == "2");
if(!timeDescendants.Any()) {
timeDescendants = document.Descendants("time")
.Where(node => (string)node.Attribute("period") == "3");
}
return timeDescendants.Take(5)
.Select(status => WeatherFactory.Create(status, city, pos))
.ToList();