Shashika Virajh
Shashika Virajh

Reputation: 9487

Filtering in Linq with where condition

I want to get the users based on the continent for my application. I used the following code for this. Now I want to show all users if the continentId is null. How can I achieve this?

public async Task<IEnumerable<User>> GetUsersByContinent(int? continentId)
{
     var users = await _context.Users
            .Include(u => u.Country).ThenInclude(c => c.Continent)
            .Where(u => u.Country.ContinentId == continentId)
            .OrderBy(u => u.Username)
            .ToListAsync();

    return users;
}

Upvotes: 1

Views: 50

Answers (2)

Orel Eraki
Orel Eraki

Reputation: 12196

I would probably use @Jehof solution, but it's worth mentioning alternative solution.

.Where(u => continentId == null || u.Country.ContinentId == continentId)

Upvotes: 1

Jehof
Jehof

Reputation: 35554

You can use use method chaining to solve your problem.

public async Task<IEnumerable<User>> GetUsersByContinent(int? continentId)
{
     var baseQuery= _context.Users.Include(u => u.Country).ThenInclude(c => c.Continent);

     if (continentId.HasValue){
         baseQuery = baseQuery.Where(u => u.Country.ContinentId == continentId)
     }

     return await baseQuery.OrderBy(u => u.Username).ToListAsync();
}

Upvotes: 1

Related Questions