With your specific 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, to apply a variety of queries, you can 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 use the conditional operator to construct the correct 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();
source share