2

我有一些我正在尝试重构的 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", ", "),
            };
}

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

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

4

3 回答 3

8
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 块中的子句。

于 2012-12-14T02:02:19.443 回答
3

一种方法可能是:

var query = from ticket in dataClassesDataContext.TicketsIssues
            where ticket.ClosedDate == null 
            select new
            {
                Priority = ticket.TicketPriority.TicketPriorityName,
                Description = ticket.Description.Replace("\n", ", "),
            };

if (!string.IsNullOrWhiteSpace(_filter.AssignedTo)
    query = query.Where(w => cUser.GetUserNameUsingGUID(w.AssignTicketToUser) == _filter.AssignedTo));
于 2012-12-14T02:02:01.623 回答
1

看看PredicateBuilder C# In a Nutshell 中的实现,该And 方法应该在这里以更通用的方式解决您的问题,并帮助建立对 LINQ 和表达式树的理解。你最终会得到类似的东西:

var query = from ticket in dataClassesDataContext.TicketsIssues
            where ticket.ClosedDate == null
            select new
            {
                Priority = ticket.TicketPriority.TicketPriorityName,
                Description = ticket.Description.Replace("\n", ", "),
            };

if (!string.IsNullOrWhiteSpace(_filter.AssignedTo))
{
     query = query.And(ticket => cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo);
}
于 2012-12-14T02:42:06.573 回答