Entity framework Select first item in group that satisfies condition or just first item

怎甘沉沦 提交于 2021-01-28 14:34:13

问题


I have a table with localized values like this

LocalizedFruits
ID | LOCALE | NAME
1  | en_UK  | Banana
2  | da_DK  | Banan
3  | de_DE  | Banane
4  | zh-CHS | 香蕉

Then i want to autocomplete the value the user is typing, if the user is chinese it's all good but if it's people from one of the other cultures a problem arises, when they type "ba" the user will get 3 results that are the same thing. therefore i group the result by Locale.

What i want to do is i want to get the group with the same locale as the user, but as the user might be typing in another language than his browser locale, there is a chance that locale does not yeld any results, therefor i would like to have the first item in group that satisfies the locale condition or if no such item is found just the first item of the group

List<LocalizedFruits> lf = db.LocalizedFruits.Where(p => p.Name.StartsWith(name))
                             .GroupBy(g => g.Locale)
                             .Select(g.First(l => l.Locale == locale) || g.First())
                             .ToList();

the last part of the query is wrong as it's not possible put an "or" there

Any Linq and Entity Framework Guru's out there who know how to construct a query that does that?


回答1:


you may just change your Select by, using the coalesce (??) operator instead of an or

.Select(g => g.FirstOrDefault(l => l.Locale == locale) ?? g.First())

or

.Select(g => g.OrderByDescending(m => m.Locale == locale).First())



回答2:


this is actually a sorting problem. if you are using Linq, I suggest to order it after load the data from db, then sort the data based on your criteria.

List<LocalizedFruits> lf = db.LocalizedFruits.Where(p => p.Name.StartsWith(name))
                         .GroupBy(g => g.Locale)
                         .ToList();
lf = lf.MakeFirst(m=> m.Locale == locale).ToList();

MakeFirst Extension:

public static class Ext
{

    public static IEnumerable<T> MakeFirst<T>(this IEnumerable<T> items, Func<T, bool> predicate)
    {
        return items.OrderBy(m => predicate(m) ? 0 : 1);
    }

    public static void Test()
    {
        var givenLocale = 1;
        var items = Enumerable.Range(0, 0).Select(m => new { Id = m, Locale = m });
        var sorted = items.MakeFirst(m => m.Locale == givenLocale).ToList();
    }
}


来源:https://stackoverflow.com/questions/20462671/entity-framework-select-first-item-in-group-that-satisfies-condition-or-just-fir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!