I know this will probably be a newbie question. Is there a way to choose different search criteria depending on the bool value? Later in the code, I want to loop through the object (alDisabledPrograms). I know the if/else is not correct, I put that in there to show how I'd like that to be handled. I attempted to place this inside a larger if/else condition but was unable to loop through alDisabledPrograms later. Thoughts?
var alDisabledPrograms = xlServerRoles.Descendants("ServerRole")
if(isDup)
{
.Where(dp => dp.Element("ServerType").Value == currentColumn.Substring(0, currentColumn.Length - 1))
}
else
{
.Where(dp => dp.Element("ServerType").Value == currentColumn)
}
.Descendants("ProgramName")
.Select(p => p.Value)
.ToList();
With your particular code, the answer is really simple:
string targetColumn = isDup ? currentColumn.Substring(0, currentColumn.Length - 1)
: currentColumn;
var alDisabledPrograms = xlServerRoles.Descendants("ServerRole")
.Where(dp => dp.Element("ServerType").Value == targetColumn)
.Descendants("ProgramName")
.Select(p => p.Value)
.ToList();
In general though, to apply very different queries, you could either use:
IEnumerable<XElement> roles = xlServerRoles.Descendants("ServerRole");
if (isDup)
{
roles = roles.Where(dp => ...);
}
else
{
roles = roles.Where(dp => ...);
}
var alDisabledPrograms = roles.Descendants(...)
...
Or you could maybe use the conditional operator to construct the right predicate:
var filter = isDup ? (Func<XElement, bool>)(dp => ...)
: (Func<XElement, bool>)(dp => ...);
var alDisabledPrograms = xlServerRoles.Descendants("ServerRole")
.Where(filter)
.Descendants("ProgramName")
.Select(p => p.Value)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With