按列排列Linq,优先使用值列

时间:2014-01-17 11:18:39

标签: linq entity-framework

我有3张桌子,

Operation

柱: idOperation int cdLangPrimary char(2)

Languages

柱: cdLang char(2) nmLang nvarchar(10)

表格OperationLanguages 专栏:idOperation int cdLang char(2)

我的代码:

var jsonObject = dbContext.Operations
                .Single(o => o.idOperation == idOperation)
                .Languages
                .Select(l => new { l.cdLang, l.nmLang });

我想做什么(没有成功), 是按-Z排序语言,但将cdLangPrimary作为第一个。

我知道如果我像这样创建一个List(或Dictionary)是可能的:

var languages = new List<Languages>();
var dLanguage = operation.Languages.Single(l => l.cdLang == operation.cdLangPRIMARY);

            languages.Add(dLanguage);

            languages.AddRange(operation.Languages.Where(l => l.cdLang != dLanguage.cdLang));

只是想知道linq是否有相同的选项 还是以更有效的方式?

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,以下内容应该这样做:

var result = dbContext.Languages
                      .Where(l => l.OperationId == idOperation)
                      .OrderByDescending(l => l.cdLang == l.Operation.cdLangPrimary)
                      .ThenBy(l => l.cdLang)
                      .Select(l => new { l.cdLang, l.nmLang });

如果您在实体框架中没有在OperationLanguage之间设置关系,那么您可以获得与以下相同的结果:

var operation = dbContext.Operations
                         .SingleOrDefault(o => o.idOperation == idOperation);

if(operation != null)
{
    var result = dbContext.Languages
                          .Where(l => l.OperationId == idOperation)
                          .OrderByDescending(l => l.cdLang == operation.cdLangPrimary)
                          .ThenBy(l => l.cdLang)
                          .Select(l => new { l.cdLang, l.nmLang });
}