Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq if/else condition?

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();
like image 350
Sparhawk Avatar asked Dec 02 '22 19:12

Sparhawk


1 Answers

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();
like image 66
Jon Skeet Avatar answered Dec 25 '22 16:12

Jon Skeet