分组麻烦

时间:2011-07-03 02:16:16

标签: c# linq group-by

您好我将这些数据分组有困难,因为它没有聚合功能。我在2个表中有以下数据,我想通过PaymentId和display only 1 row of record加入。

enter image description here

问题:
如何仅在CourseAdidForMonthYear中以 1 ROW 组显示最终结果。
我想从Payment.*, TutorCourseCommissions.* and CoursePaidForMonthYear column in same row displaying (September, October, November)

获取所有数据

示例:

referenceId| TutorId| CoursePaidForMonthYear                 |  
1          | 1019   | September, October, November OR 9,10,11|

我的工作:

 var result = from u in db.Users
                    join p in db.Payments on u.Id equals p.UserId
                    join tt in db.TutorCourseCommissions on p.Id equals tt.PaymentId into gtt
                        from tt in gtt.DefaultIfEmpty()                       
                    where u.Id == user.Id
                    GroupBy tt.CoursePaidForMonthYear  ??
                    select new { u, p, tt };

            foreach (var r in result)
            {
                Payment payment = new Payment();                  
                payment.MonthToPay = (r.tt == null) ? null : common.GetMonthName(r.tt.CoursePaidForMonthYear.Month, true);
                payment.Amount = r.p.Amount;                    

                output.Add(payment);
            }
            return output;

2 个答案:

答案 0 :(得分:1)

您需要做的是按用户和付款对月份进行分组,然后对分组的月份执行汇总。在这种情况下,我使用String.Join()来组合来自佣金的不同月份。

这将为您提供{ User = "John Doe", Payment = ..., Months = "January, February" }

的结果
var result = from u in db.Users
              where u.UserID == user.Id
              join p in db.Payments on u.Id equals p.UserId
              join comm in db.TutorCourseCommissions 
              on p.Id equals comm.PaymentId
              group common.GetMonthName(comm.CoursePaidForMonthYear,true)
              by new { User = u, Payment = p } into g
              select new 
              {
                 User = g.Key.User,
                 Payment = g.Key.Payment,
                 //...select out other properties here... 
                 Months = String.Join(", ", g.Distinct())
              };

答案 1 :(得分:0)

创建一个包含所需列的属性的类,然后使用其实例进行选择...

喜欢

public TutorPayments
{

 public int UserID{
 get;
 set;
}

 public int PayType{
 get;
 set;
  }

  public int TutorID{
  get;
 set;
  }

 //and so on all columns property that you required
}

现在您可以通过以这种方式创建其实例来获取查询中的所有这些

   var result = from u in db.Users
                join p in db.Payments on u.Id equals p.UserId
                join tt in db.TutorCourseCommissions on p.Id equals tt.PaymentId into gtt
                    from tt in gtt.DefaultIfEmpty()                       
                where u.Id == user.Id
                GroupBy tt.CoursePaidForMonthYear  ??
                select new TutorPayments {UserID =  u.id,PayType = p.id,TutorID = tt.TutorId, ............ };