LINQ multiple grouping criteria RRS feed

  • Question

  • I have a query:

                            var orders = from o in orderHistory
                                         group o by new { categoryDictionary[o.Sku][0].Category, categoryDictionary[o.Sku][0].SubCategory } into categoryList
                                         select new
                                             Category = categoryList.Key.Category,
                                             SubCategory = categoryList.Key.SubCategory,
                                             Summary = from h in categoryList
                                                       group h by h.Date.Year * 100 + ((h.Date.Day > 15) ? h.Date.Month * 2 : h.Date.Month * 2 - 1) into skuHistory
                                                       orderby skuHistory.Key
                                                       select new { Period = skuHistory.Key, Quantity = skuHistory.Sum(s => s.Quantity) }

    But if I change the anonymous type for group by adding ".Trim()" I get the error

    Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

    If it is illegal to put this in an anonymous type then is there another way to group by multiple criteria? Or is there some "trick" that I can get these strings into an anonymous type?

    Thank you.



    Wednesday, May 20, 2009 5:44 PM


  • Can you show us the query that gives the error?
    If you want to use the Trim method in defining a value of a property of your grouping key then you need to make sure you define the member name e.g.

     var orders = from o in
    group o by new { Category = categoryDictionary[o.Sku][0].Category.Trim(), SubCategory = categoryDictionary[o.Sku][0].SubCategory.Trim() } into categoryList

    MVP XML My blog
    • Marked as answer by KevinBurton Wednesday, May 20, 2009 5:54 PM
    Wednesday, May 20, 2009 5:50 PM