如何在LINQ中执行GroupBy多列,我还想采用一些列:
public class Notification
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public long NotificationId { set; get; }
public NotificationType NotificationType { set; get; }
public int UserId { get; set; }
public UserProfile UserProfile { get; set; }
public DateTime CreateDate { set; get; }
public bool Notice { set; get; }
public long NewsId { set; get; }
public int RecipientId { get; set; }
}
我编写了以下代码,但显示了所有记录:
var x=(from n in _Notification
where n.RecipientId == id
orderby n.CreateDate descending, n.UserId
group new { n.UserId, n.NewsId}
by new { n.UserId, n.NewsId, n.Notice, n.NotificationType, n.CreateDate, n.NotificationId, n.UserProfile } into g
select new NotificationViewModel
{
NewsId = g.Key.NewsId,
CauserId = g.Key.UserId,
CauserName = g.Key.UserProfile.Name,
CreateDate = g.Key.CreateDate,
Notice = g.Key.Notice,
NotificationId = g.Key.NotificationId,
NotificationType = g.Key.NotificationType,
}).ToList();
我想根据UserId和NewsId
进行分组答案 0 :(得分:1)
您会列出一个而不是分组列表,因为最后您有select语句,而您最后应该有group by。像这样更改你的代码:
var x=(from n in _Notification
where n.RecipientId == id
orderby n.CreateDate descending, n.UserId
group new NotificationViewModel
{
NewsId = g.Key.NewsId,
CauserId = g.Key.UserId,
CauserName = g.Key.UserProfile.Name,
CreateDate = g.Key.CreateDate,
Notice = g.Key.Notice,
NotificationId = g.Key.NotificationId,
NotificationType = g.Key.NotificationType,
}
by new { n.UserId, n.NewsId}).ToList();