使用group by为对象列表创建属性总和

时间:2011-07-17 15:55:01

标签: linq

List<Budget> list1 = new List<Budget>();

list1.Add(new Budget(){

    SeasonNo = "31",
    SeasonName = "season1",
    typeProductCd = "1",
    typeProductDescription = "typeproduct1",
    UsdActualRetail = 500,
} );


List<Budget> list2 = new List<Budget>();

list1.Add(new Budget()
{

    SeasonNo = "31",
    SeasonName = "season1",
    typeProductCd = "1",
    typeProductDescription = "typeproduct1",
    UsdActualRetail = 600,
});
List<Budget> list1and2Ungrouped = list1.Concat(list2).ToList();


public class Budget
{
    public Int32 CatalogueId { get; set; }
    public string CustomerNo { get; set; }
    public string SeasonNo { get; set; }
    public string SeasonName { get; set; }
    public string typeProductCd { get; set; }
    public string typeProductDescription { get; set; }
    //public string RetailDept { get; set; }
    public Decimal UsdBudgetRetail { get; set; }
    public Decimal UsdActualRetail { get; set; }

    public Decimal UsdPercentBought
    {
        get
        {
            return (UsdActualRetail != 0) ? Math.Round((UsdActualRetail / UsdBudgetRetail) * 100, 2) : 0;
        }

    }


    public Decimal BudgetNoOfSku { get; set; }
    public Decimal ActualtNoOfSku { get; set; }



    public Decimal SkuPercentBought
    {
        get
        {
            return (ActualtNoOfSku != 0) ? Math.Round((ActualtNoOfSku / BudgetNoOfSku) * 100, 2) : 0;
        }

    }
}

我希望首先在season_no上列出我的列表,而不是在typeProductCd上,而不是将usdActualRetail的总和用于相同类型的ProductCd

我想获得新列表所以我可以在报告中显示它 例如,在我的报告中,我将:

 season number1   31
          typeProductCd1  10
              typeProductDescription   sum of usd actual retail  
               ....                      .......

 season number2   32
          typeProductCd1  11
              typeProductDescription   sum of usd actual retail  
               ....                         .......

1 个答案:

答案 0 :(得分:0)

我认为这与Group By Multiple Columns - LINQ

有点相同
        var q = from ll in list1and2Ungrouped
                group ll by new { ll.SeasonNo, ll.typeProductCd } into g
                select new
                {
                    g.Key,
                    val = g.Sum(p => p.UsdActualRetail)
                };

        //here is how the data looks
        foreach (var a in q)
        {
            string SeasonNo = a.Key.SeasonNo;
            string typeProductCd = a.Key.typeProductCd;
            decimal val = a.val;
        }