开发者

How can I get two different aggregates in a single 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 preparation for making a chart displayed on a dashboard I am trying 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:

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

I am having a hard time coming up with 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 obviou开发者_StackOverflow中文版s problem in is the "Purchased = g.Count()" line in that it just repeats the Trials result. I would like to count objects where the BillingStartDate.HasValue is true.

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

Edit: I would prefer a fluent style of syntax but I was unable to get the above to work. Answer in any variation would be great.


You need to pass a condition to the Count method.

Purchased = g.Count(q => q.BillingStartDate.HasValue)


So SLaks had the right solution. Here it is written in fluent 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)
                                });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜