Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - if condition

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);
like image 952
ilija veselica Avatar asked Jun 16 '10 08:06

ilija veselica


2 Answers

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"))
like image 102
GvS Avatar answered Oct 12 '22 02:10

GvS


// This is critical part
Status = deals.Any() ? "Client" : "Prospect"
// End of critical part...
like image 31
LukeH Avatar answered Oct 12 '22 04:10

LukeH