简体   繁体   中英

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

I have aa 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;

}

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.

You can include the HasValue check in the where clause:

public List<Language> GetLanguageList(LanguageMapper ctx, int? languageId)
{

    List<Language> languages = ctx.LANGUAGELIST
                                    .Where(e => !languageId.HasValue || e.LanguageId == languageId)
                                    .Select(e => new Language()
                                    {
                                        LanguageId = e.LANGUAGEID,
                                        LanguageName = e.LANGUAGE
                                    })
                                    .ToList();                    

    return languages;

}

Note: pswg's answer will lead to cleaner, more efficient sql in the instance where languageId is null in this particular example, but its worth seeing that this option is available for more complex examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM