在代码中,注释部分是我需要解决的问题…有没有办法在LINQ中编写这样的查询?我需要这个,因为我需要根据状态进行排序.
var result = ( from contact in db.Contacts join user in db.Users on contact.CreatedByUserID equals user.UserID join deal in db.Deals on contact.ContactID equals deal.ContactID into deals orderby contact.ContactID descending select new ContactListView { ContactID = contact.ContactID,FirstName = contact.FirstName,LastName = contact.LastName,Email = contact.Email,Deals = deals.Count(),EstValue = deals.Sum(e => e.EstValue),SalesAgent = user.FirstName + " " + user.LastName,Tasks = 7,// This is critical part if(Deals == 0) Status = "Prospect"; else Status = "Client"; // End of critical part... }) .OrderBy(filterQuery.OrderBy + " " + filterQuery.OrderType) .Where(filterQuery.Status);
解决方法
Status = (deals.Count() == 0 ? "Prospect" : "Client")
The conditional operator (?:) returns
@H_502_17@
one of two values depending on the
value of a Boolean expression.编辑:你可以像这样组合:
Status = (deals.Count() == 0 ? "Prospect" : (deals.Count() == 1 ? "Client" : "Other"))在这种情况下,您正在使用deals.Count(),因此您可以使用LINQ let语法将结果存储在临时变量中:
var result = ( from contact in db.Contacts join user in db.Users on contact.CreatedByUserID equals user.UserID join deal in db.Deals on contact.ContactID equals deal.ContactID into deals let dealCount = deals.Count() ... // Continue here Status = (dealCount == 0 ? "Prospect" : (dealCount == 1 ? "Client" : "Other"))