I have some linq code that I am trying to refactor because its not very good:
Basically, I am wondering if there is a better way to perform the following:
if (!string.IsNullOrWhiteSpace(_filter.AssignedTo)
{
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
&& cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
}
else
{
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
}
They are both identical apart from the where clause is checks for AssignTicketToUser.
I am hoping there is a nicer way to do this to avoid having to use an if else statement? I have a few of these code blocks and dont want to be duplicating code alot!
You can get rid of the if-else statement altogether. Transfer the if condition it to the 2nd where clause, and remove the !. That second where clause becomes a ternary operator.
If the condition is true, that is if _filter.AssignedTo is null, then don’t test _filter.AssignedTo by returning true. If it’s not null or empty, then proceed to the clause that was there in your original else block.