Entity Framework - LINQ statement with WHERE clause based on NULLABLE parameter

c#, entity-framework, linq

Solution

Just do the `.Where` before the `.Select`, like this:

public List<Language> GetLanguageList(LanguageMapper ctx, int? languageId)
{
    var query = ctx.LANGUAGELIST.AsQueryable();
    if (languageId.HasValue)
    {
        query = query.Where(x => x.LanguageId == languageId.Value);
    }

    List<Language> languages = query.Select(e => new Language()
                                    {
                                        LanguageId = e.LANGUAGEID,
                                        LanguageName = e.LANGUAGE
                                    })
                                    .ToList();                    
    return languages;
}

By using `IQueryable<Language>` in this way, you ensure that only one call is made to the database, regardless of what parameters are passed to this method.

Problem

I have a a method that return a list of languages. It has a nullable parameter of languageId. If passed, the method returns that language otherwise returns the list of languages. I want to know if I can simplify this piece of code to have a select and where clause in one statement. ``` public List<Language> GetLanguageList(LanguageMapper ctx, int? languageId) { List<Language> languages = ctx.LANGUAGELIST .Select(e => new Language() { LanguageId = e.LANGUAGEID, LanguageName = e.LANGUAGE }) .ToList(); if (languageId.HasValue) { languages = languages.Where(x => x.LanguageId == languageId).ToList(); } return languages; } ```

Original source