How can I get two different units in one LINQ?

I have a list of this object:

public class Customer { public int Id { get; set; } public string EmailAddress { get; set; } public DateTime ServiceStartDate { get; set; } public DateTime? BillingStartDate { get; set; } public string Status { get; set; } } 

In the process of preparing the chart displayed on the dashboard, I try to condense this list into another list of this object:

 public class DashboardCustomerConversions { public string Month { get; set; } public int Trials { get; set; } public int Purchased { get; set; } } 

Where the end result looks something like this:

 Month Trials Purchases --------- ------ --------- Dec 2010 390 250 Jan 2011 345 190 Feb 2011 576 340 

I find it difficult to find a LINQ statement that can achieve the desired end result. This statement is very close:

 var list = from b in results group b by new { b.ServiceStartDate.Year, b.ServiceStartDate.Month } into g select new Test { Month = string.Format("{0} {1}", CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(g.Key.Month), g.Key.Year), Trials = g.Count(), Purchased = g.Count() }; 

The obvious problem is the line "Acquired = g.Count ()", in which it simply repeats the result of Trials. I would like to count objects where the value of BillingStartDate.HasValue is true.

Is there a way to restructure LINQ to make this work?

Edit: I would prefer a loose syntax style, but I was not able to get the above to work. The answer in any case will be wonderful.

+4
source share
2 answers

You need to pass the condition to the Count method.

 Purchased = g.Count(q => q.BillingStartDate.HasValue) 
+3
source

So, SLaks had the right decision. Here it is written in free syntax:

 listOfCustomer.GroupBy(c => new { c.ServiceStartDate.Year, c.ServiceStartDate.Month }) .Select(group => new DashboardCustomerConversions() { Month = string.Format("{0} {1}", CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(group.Key.Month), group.Key.Year), Trials = group.Count(), Purchased = group.Count(c => c.BillingStartDate.HasValue) }); 
+2
source

All Articles