给出以下课程:
public class SessionData
{
public Guid Session { get; set; }
public DateTime Date { get; set; }
}
并列出了一个清单:
public static List<SessionData> GetSessionData()
{
Guid guid1 = Guid.NewGuid();
Guid guid2 = Guid.NewGuid();
List<SessionData> sessionData = new List<SessionData>
{
new SessionData {Session = guid1, Date = DateTime.UtcNow.AddMinutes(3)},
new SessionData {Session = guid1, Date = DateTime.UtcNow.AddMinutes(2)},
new SessionData {Session = guid2, Date = DateTime.UtcNow.AddMinutes(5)},
new SessionData {Session = guid2, Date = DateTime.UtcNow.AddMinutes(4)},
new SessionData {Session = guid1, Date = DateTime.UtcNow.AddMinutes(20)},
new SessionData {Session = guid1, Date = DateTime.UtcNow.AddMinutes(25)},
new SessionData {Session = guid2, Date = DateTime.UtcNow.AddMinutes(20)},
new SessionData {Session = guid1, Date = DateTime.UtcNow.AddMinutes(1)},
};
return sessionData;
}
我想找到会话的平均持续时间(1)和最长的会话(2)。还有每天(3),每周(4),月(5),年(6),总数(7)有多少次会议?
我试图从
开始var list = (from t in sessionData group t.Date by t.Session).ToList();
并尝试查找每个会话的持续时间(最长日期 - 最短日期)并从那里继续。有没有更好的方法直接用Linq进行这些计算?
答案 0 :(得分:0)
var sessionData = GetSessionData();
var longestSession = sessionData
.GroupBy(sd => sd.Session)
.Select(group => new Tuple<Guid, TimeSpan>(group.First().Session, group.Max(sd => sd.Date) - group.Min(sd => sd.Date)))
.OrderBy(tuple => tuple.Item2)
.Last()
.Item1;
var averageDuration = sessionData
.GroupBy(sd => sd.Session)
.Select(group => new Tuple<Guid, TimeSpan>(group.First().Session, group.Max(sd => sd.Date) - group.Min(sd => sd.Date)))
.Average(tuple => tuple.Item2.Minutes);
对于您的其他问题,我没有立即的LINQ解决方案,我会在得到想法后立即更新。