C#如何按时间戳分组记录? [英] C# how to group records by timestamp?

查看:367
本文介绍了C#如何按时间戳分组记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#NHibernate创建一个仪表板,我想要做的是按时间戳对记录进行分组,所以如果有相同的时间戳,它只会显示一次。我已经尝试过Last(t => t.timestamp)但是收到错误,无法将类型System.DateTime转换为bool,当我尝试.GroupBy(t => t.timestamp)时,我得到< IGrouping< DateTime,Answer> ;不包含eventId,userId和timestamp字段的定义。







开放给建议。谢谢



我的尝试:



I am using C# NHibernate to create a dashboard and what I am trying to do is group the records by timestamp so if there are identical timestamps it will only show once. I have tried Last(t => t.timestamp) but receive the error of cannot convert type System.DateTime to bool and when I tried .GroupBy(t => t.timestamp) I get <IGrouping<DateTime, Answer> does not contain a definition for my fields of eventId, userId, and timestamp.



Open to suggestions. Thanks

What I have tried:

public ActionResult Dashboard()
        {
            using (ISession session = OpenNHibernateSession.OpenSession())
            {

               /*These answers gets my list of data. Here is where I am trying 
                 to use a GroupBy clause so records with identical timestamps
                 will only be shown once.*/
                var answers = session.Query<Answer>().OrderByDescending(t => t.timestamp).ToList();
               
                var dashboardVms = new List<DashboardViewModel>();
                foreach (var answer in answers)
                {
                    var dashboardVm = new DashboardViewModel
                    {
                        EventName = session.Get<Event>(answer.eventId, LockMode.Read).name,
                        EventId = answer.eventId,
                        UserId = answer.userId,
                        TimeStamp = answer.timestamp
                    
                    };
                    dashboardVms.Add(dashboardVm);
                }
                
                return View(dashboardVms);
            }
             
        }

推荐答案

我认为你可以这样做:

I think you can do something like this:
session
    .Query<Answer>()
    .OrderByDescending(t => t.timestamp)
    .GroupBy(x => x.timestamp)
    .Select(x => new
    {
        EventName = session.Get<Event>(x.eventId, LockMode.Read).name,
        EventId = x.eventId,
        UserId = x.userId,
        TimeStamp = x.Key
    }).ToList();



你如果Select调用与您的提供商不兼容,可能希望在GroupBy和select之间链接AsEnumerable调用。


You might want to chain an AsEnumerable call between the GroupBy and the select if the Select call in not compatible with your provider.


这篇关于C#如何按时间戳分组记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆