C# 如何根据条件按1个表达式或2个表达式排序?
我在一个结果中显示企业和人员,并希望将它们一起订购 伪代码:C# 如何根据条件按1个表达式或2个表达式排序?,c#,linq,.net-core,entity-framework-core,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
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表达式,如果记录是一个企业,则只按企业名称排序,否则按个人的名字和姓氏排序。我能得到的最接近的是以下内容,其中始终包括按个人姓氏排序(即使是企业)
它转换为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
这就是我希望能够写的(显然,对于错误的部分,这不是正确的语法):
从技术上讲,这并没有太大的区别(如果是一家企业,个人的名字和姓氏将为空,因此订单应该不会受到影响)。但是SQL仍然会尝试按它不需要做的事情排序
var result =
whereQuery
.OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName)
.ThenBy(x => x.BusinessName != null ? x.BusinessName : x.PersonLastName);
如果
BusinessName
不为空,则会有一个冗余的第二个排序,但查询分析器(解析SQL后的下一步)应该能够删除该冗余。修改代码如下:
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);
选择name并确保它不为null,然后按此字段排序。我认为这等同于我的代码,只是null检查位于不同的位置?看起来它仍然会包含order by person last name,即使是对于一个企业也是如此。我最喜欢这个,因为
ThenBy
在企业中不会有任何影响(正如您所提到的),而且您不需要修改查询本身。请注意,ThenBy
只需订购领带。@DavidSpence是。查询分析器的输出形式是什么样的?对不起,我按enter键太快了。这产生了两个案例陈述,但正如您所说,可能存在一些优化。我去看看。如果[o].[Name]不为空,则按大小写排序[o].[Name]ELSE[b].[LastName]结束,如果[o].[Name]不为空,则按大小写排序[o].[Name]ELSE[b].[FirstName]END@DavidSpence:当然,这些优化是由数据库而不是实体框架完成的。该sql将被发送到rdbms。但即使数据库很蠢,这也不会有什么坏处。结果将是相同的,额外的订单将只适用于领带(如果是重复的企业名称)。
var result =
whereQuery
.OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName)
.ThenBy(x => x.BusinessName != null ? x.BusinessName : x.PersonLastName);
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);