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

问题描述 投票:4回答:2

我在一个结果中展示企业和人,并希望一起订购。

伪代码:

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仍然会尝试按照它不需要做的事情进行排序。

c# linq .net-core entity-framework-core
2个回答
4
投票
var result =
  whereQuery
    .OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName)
    .ThenBy(x => x.BusinessName != null ? x.BusinessName : x.PersonLastName);

BusinessName不为空的情况下,将存在冗余的第二个排序,但查询分析器(解析SQL之后的下一步)应该能够删除该冗余。


3
投票

像这样修改你的代码:

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
    {
        Name = business.Name ?? person.FirstName,
        person.LastName
    };

var result = whereQuery
        .OrderBy(x => x.Name)
        .ThenBy(x => x.PersonLastName);

选择名称并确保它不为空,然后按此字段排序。

© www.soinside.com 2019 - 2024. All rights reserved.