gpt4 book ai didi

时间:2019-03-08 标签:c#linqwhereconditionalif

转载 作者:行者123 更新时间:2023-11-30 19:06:10 27 4
gpt4 key购买 nike

我有一些我正在尝试重构的 linq 代码,因为它不是很好:

基本上,我想知道是否有更好的方法来执行以下操作:

if (!string.IsNullOrWhiteSpace(_filter.AssignedTo)
{
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
&& cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
}
else
{
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
}

除了检查 AssignTicketToUser 的 where 子句外,它们都是相同的。

我希望有更好的方法来避免使用 if else 语句?我有一些这样的代码块,不想重复很多代码!

最佳答案

var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
&& (string.IsNullOrWhiteSpace(_filter.AssignedTo) ? true : cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo)
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};

您可以完全摆脱 if-else 语句。将 if 条件转移到第二个 where 子句,并删除 !。第二个 where 子句成为三元运算符。

如果条件为真,即如果_filter.AssignedTo 为null,则不要通过返回true 来测试_filter.AssignedTo。如果它不为 null 或为空,则继续执行原始 else block 中的子句。

关于时间:2019-03-08 标签:c#linqwhereconditionalif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13871583/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com