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

时间:2017-12-18 15:41:10

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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);

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