how to use switch case statement to filter result set based on condition in c#

89 Views Asked by At

i am working on a task where i am sending a status as parameter in request and want to filter based on that status and one other column from database table but that is not passed from request.

so it is like

when status is incomplete and Key value in db is null then fetch records fullfilling this criteria (awaiting)

when status is incomplete and Key value in db is not null then fetch records fullfilling this criteria (pending review)

when status is suspended then fetch records fullfilling this criteria (rejected)

when status is Succeeded then fetch records fullfilling this criteria (approved)

when status is Failed then fetch records fullfilling this criteria (Failed)

public class StatusRequest
{
    public Status Status { get; set; }
}

public Task<StatusSearchResponse> Handle(StatusRequest request)
{
var projects = Repository.GetProjects(request.Status);
switch (request.Status)
{
    case Status.Incomplete && projects .Any(x => x.Key == null):
        projects.Where(x => x.Status == Status.Incomplete && x.Key == null);
        break;
    case Status.Suspended:
        break;
    case Status.Succeeded:
        break;
    case Status.Failed:
        break;
    default:
        throw new ArgumentOutOfRangeException();
}

var response = new StatusSearchResponse();
response.Projects = projects;
return SystemTask.FromResult(response);
}

so my code is as follows Or without switch statement can i use stored procedure to do so can anybody suggest please

1

There are 1 best solutions below

1
Hans Kesting On

projects.Where(...) doesn't "do" anything to 'projects' but it returns a new list (enumerable).

So change that line to

projects = projects.Where(x => x.Status == Status.Incomplete && x.Key == null).ToList();
  • You probably need a .ToList() to convert from the IEnumerable that .Where() returns to a list (that I assume 'projects' is)
  • And (important!) assign that list back to 'projects'