【问题标题】:group by multiple Columns and Select specific columns按多个列分组并选择特定列
【发布时间】:2014-06-27 10:25:08
【问题描述】:

如何在 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进行分组

【问题讨论】:

    标签: c# entity-framework group-by linq-to-entities multiple-columns


    【解决方案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();
    

    【讨论】:

    • 谢谢。现在如何转换 Ilist。 (x 是 IGrouping,我有点想要 IList IList
    • x 将是 List> 类型,因此它是 NotificationViewModel 列表的列表
    • IGrouping 扩展了 IEnumerable
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多