Search code examples
c#linqentity-framework-core

How to simplify this LINQ WHERE query?


I'm trying to select several rows from a table but would like the selection to stop if the first where clause comes back with results. Basically if there are results with language then I don't need to query for DevLanguage or FallbackLanguage, is this possible in a single query with || operator or with some other LINQ magic?

        var languageStrings = _presentationContext.LocalizationStrings
            .Where(x => x.Namespace.Namespace == @namespace &&
                        x.Namespace.Language == language);

        var devStrings = _presentationContext.LocalizationStrings
            .Where(x => x.Namespace.Namespace == @namespace &&
                        x.Namespace.Language == Constants.DevLanguage);

        var fallbackStrings = _presentationContext.LocalizationStrings
            .Where(x => x.Namespace.Namespace == @namespace &&
                        x.Namespace.Language == Constants.FallbackLanguage);

        var localizationStrings = languageStrings.Any() ? languageStrings : devStrings.Any() ? devStrings : fallbackStrings.Any() ? fallbackStrings

Solution

  • I would put the common part of these queries into a separate query.

    var query = _presentationContext.LocalizationStrings.Where(x => x.Namespace.Namespace == @namespace);
    
    var languageStrings = query.Where(x => x.Namespace.Language == language);
    var devStrings = query.Where(x => x.Namespace.Language == Constants.DevLanguage);
    var fallbackStrings = query.Where(x => x.Namespace.Language == Constants.FallbackLanguage);
    

    The SQL is generated the same.