In code, the commented part is what I need to solve... Is there a way to write such query in LINQ? I need this because I will need sorting based on Status.
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")
This uses the "Conditional operator"
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
Edit: You can make combinations like this:
Status = (deals.Count() == 0 ? "Prospect" : (deals.Count() == 1 ? "Client" : "Other"))
In this case your are using deals.Count(
) a lot, so you can store the result in a temporary variable using the LINQ let
syntax:
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"))
// This is critical part
Status = deals.Any() ? "Client" : "Prospect"
// End of critical part...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With