Linq-一对多关系,按规则排序

时间:2019-07-13 18:12:15

标签: c# linq entity-framework-core

我有3张桌子:

TranslationCode:
  Id  Name
  1   'User'
  2   'Role'

Language:
  Id
   1
   2
Translation:
 TranslationCodeId  LanguageId  StoreId (Allow Null) Value
   1                   2           null               'User'
   1                   2           1                  'Person'
   2                   1           null               'Роль'

我需要选择所有带有TranslationCodeId的翻译,并且Value取决于LanguageId和OrganizationId。 例如:

LanguageId = 2 StoreId = null
TranslationCodeId  Value
 1                 'User'
 2                 'Роль'

LanguageId = 2 StoreId = 1
TranslationCodeId  Value
 1                 'Person'
 2                 'Роль'

我通过这种方式实现

var languageId = 2;
IEnumerable<object> result = _unitOfWork.DbContext.Set<TranslationCode>().Select(t => new {
    t.Id,
    v = (
         t.Translations.Any(l => l.StoreId == storeId && l.LanguageId == languageId) ? t.Translations.First(l => l.StoreId == storeId && l.LanguageId == languageId).Value :
         t.Translations.Any(l => l.LanguageId == languageId) ? t.Translations.FirstOrDefault(l => l.LanguageId == languageId).Value :
         t.Translations.FirstOrDefault().Value
     )
});

有人有更优雅的主意吗?

1 个答案:

答案 0 :(得分:3)

  

有人有更优雅的主意吗?

好吧,答案在问题标题中-按规则排序,即按所需元素的优先级对序列进行排序,而不是第一个,例如:

v = t.Translations
    .OrderBy(l => l.LanguageId == languageId ? (l.StoreId == storeId ? 0 : 1) : 2)
    .Select(l => l.Value)
    .FirstOrDefault()