c# - 如何根据条件按 1 个表达式或 2 个表达式排序?

标签 c# linq .net-core entity-framework-core

我在一个结果中显示商家和人员,并希望将它们一起订购。

伪代码:

if business name is not null
order by business name
else
order by first name then last name

我构建了 LINQ 查询,它连接到多个表(并且工作正常),大致如下所示。

var query = from x in ...
    join business in dbContext.Businesses on ...
    from businesses in bus.DefaultIfEmpty()
    join person in dbContext.People on ...
    from people in peo.DefaultIfEmpty()
    select new Party
    {
        person.FirstName,
        person.LastName,
        business.Name,
    };

我不知道如何编写一个 LINQ 表达式,如果记录是企业,则仅按企业名称排序,否则按人的名字和姓氏排序。我能得到的最接近的是以下内容,其中始终包括按人姓氏排序(即使对于企业也是如此)。

var result =
    whereQuery
        .OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName)
        .ThenBy(x => x.PersonLastName);

转换成SQL:

ORDER BY CASE
    WHEN [business].[Name] IS NOT NULL
    THEN [business].[Name]
    ELSE [person].[FirstName]
END, [person].[LastName]

我想要的是:

ORDER BY CASE
    WHEN [business].[Name] IS NOT NULL
    THEN [business].[Name]
    ELSE [person].[FirstName], [person].[LastName]
END

这是我希望能够写的(显然错误部分的语法不正确):

var result =
        whereQuery
            .OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName, x.PersonLastName);

从技术上讲,这并没有太大的区别(如果是企业,人的名字和姓氏将为空,因此顺序应该不会受到影响)。但是 SQL 仍会尝试按它不需要执行的操作进行排序。

最佳答案

var result =
  whereQuery
    .OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName)
    .ThenBy(x => x.BusinessName != null ? x.BusinessName : x.PersonLastName);

BusinessName 不为 null 的情况下会有冗余的二阶排序,但查询分析器(解析 SQL 后的下一步)应该能够删除该冗余。

关于c# - 如何根据条件按 1 个表达式或 2 个表达式排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47871750/

相关文章:

c# - 在不违反 SOLID 原则的情况下添加条件逻辑 C#

c# - 如何在 C# 中解决此错误?

c# - OAEP RSA 参数与 RSACryptoServiceProvider.Encrypt

c# - 无法将图像添加到 C# WPF .Net Core WPF 应用程序

c# - 在 C# 中合并重叠的 url

c# - Visual Studio Ordered 测试运行两次

c# - 使用默认构造函数初始化类型 C#

c# - 使用逻辑或对多个属性进行分组

c# - 使用 Linq 查找重复行

.net-core - 无法让 xUnit 测试与 .NET Core 一起运行