在ViewModel中获取分组数据

时间:2014-12-08 07:40:19

标签: sql linq entity-framework

我有以下数据::

(I/P)
UserID  Name        Date        Amount
1       Rahul    2014-04-01     10
1       Rahul    2014-05-01     20
1       Rahul    2014-06-01     30
1       Rahul    2014-07-01     40
1       Rahul    2014-08-01     50
1       Rahul    2014-09-01     60
1       Rahul    2014-10-01     70

我希望我的输出为::

(O/P)
UserID      Name    First               Second              Third               Fourth              Fifth
1           Rahul    (2014-04-01,10)    (2014-05-01,20)     (2014-06-01,30)     (2014-07-01,40)     (2014-08-01,50)

我正在使用LINQ查询但是如何获得我预期的上述输出。 在SQL或LINQ中。

1 个答案:

答案 0 :(得分:1)

我已经回答了我自己的问题, 与他人分享以供将来参考

1) 我将两个ViewModel设为::

  public class MonthViewModel
    {
        public DateTime MonthName { get; set; }
        public decimal Amount { get; set; }
    }

    public class ParentViewModel 
    {
        public long ID { get; set; }
        public string Name { get; set; }

        //For Months
            public decimal FirstMonth { get; set; }
            public decimal SecondMonth { get; set; }
            public decimal ThirdMonth { get; set; }
            public decimal FourthMonth { get; set; }
            public decimal FifthMonth { get; set; }
            public decimal SixthMonth { get; set; }           
    }

2)然后以类似::

的格式获取数据
(I/P)
UserID  Name        Date        Amount
1       Rahul    2014-04-01     10
1       Rahul    2014-05-01     20
1       Rahul    2014-06-01     30
1       Rahul    2014-07-01     40
1       Rahul    2014-08-01     50
1       Rahul    2014-09-01     60
1       Rahul    2014-10-01     70

我正在使用LINQ + Pivot功能::

DateTime CurrentDate = Datetime.UtcNow;
var DetailsList = DataList
            .GroupBy(x => new { x.ID, x.Name })
            .Select(x => new ParentViewModel
                        {
                            ID=x.Key.ID,
                            Name=x.Key.Name,
                            FirstMonth=x.Where(y=>y.Month==CurrentDate).Sum(y=>y.Amount) ,
                            SecondMonth=x.Where(y=>y.Month==CurrentDate.AddMonths(-1)).Sum(y=>y.Amount) ,
                            ThirdMonth=x.Where(y=>y.Month==CurrentDate.AddMonths(-2)).Sum(y=>y.Amount) ,
                            FourthMonth=x.Where(y=>y.Month==CurrentDate.AddMonths(-3)).Sum(y=>y.Amount) ,
                            FifthMonth=x.Where(y=>y.Month==CurrentDate.AddMonths(-4)).Sum(y=>y.Amount) ,
                        }
            ).ToList();

多数民众赞成。