作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些我正在尝试重构的 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/
我有一些我正在尝试重构的 linq 代码,因为它不是很好: 基本上,我想知道是否有更好的方法来执行以下操作: if (!string.IsNullOrWhiteSpace(_filter.Assign
我是一名优秀的程序员,十分优秀!