May 13, 2014

Multiple group by and Sum LINQ

var products = new[] {
    new {SaleDate = new DateTime(2009,10,22), Product = "Soap", Quantity = 10},
    new {SaleDate = new DateTime(2009,09,22), Product = "Pills", Quantity = 5},
    new {SaleDate = new DateTime(2009,09,25), Product = "Soap", Quantity = 6},
    new {SaleDate = new DateTime(2009,09,25), Product = "Pills", Quantity = 15}
};

var summary = from p in products
              let k = new
              {
                   //try this if you need a date field 
                   //   p.SaleDate.Date.AddDays(-1 *p.SaleDate.Day - 1)
                  Month = p.SaleDate.ToString("MM/yy"),
                  Product = p.Product
              }
              group p by k into t
              select new
              {
                  Month = t.Key.Month,
                  Product = t.Key.Product,
                  Qty = t.Sum(p => p.Quantity)
              };

foreach (var item in summary)
    Console.WriteLine(item);
var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

            var consolidatedChildren = collection.GroupBy(p => new
                {
                    c.School,
        c.Friend,
        c.FavoriteColor,
}) .Select(p => p.ToList()); foreach (var childList in consolidatedChildren ) { foreach (Children child in childList) {
}
}

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib