我的数据结构如下所示。对于每个(人,游戏)对,我需要找到过去24小时内的最新分数。在LINQ中可以这样做吗?像(人物,游戏,最新分数)
的东西+----------------+-----------------+---------------+-+------------+
| Person | Game | Score |EventTime |
+-----------------------------------------------------------------+
| | | | |
| | | | |
+----------------+-----------------+---------------+--------------+
任何提示都会非常有用。
答案 0 :(得分:3)
假设您有这样的课程:
class GameInfo
{
public DateTime EventTime { get; set; }
public String Game { get; set; }
public String Person { get; set; }
public double Score { get; set; }
}
你可以这样做:
List<GameInfo> data = new List<GameInfo> {
new GameInfo { Game = "G1", Person = "A", Score = 10, EventTime = new DateTime(2014, 10, 10, 10, 10, 10) },
new GameInfo { Game = "G1", Person = "A", Score = 10, EventTime = new DateTime(2014, 10, 10, 10, 10, 10) },
new GameInfo { Game = "G2", Person = "B", Score = 11, EventTime = new DateTime(2014, 10, 10, 20, 10, 10) },
new GameInfo { Game = "G2", Person = "B", Score = 11, EventTime = new DateTime(2014, 10, 10, 20, 10, 10) }
};
var q = from game in data
group game by new { G = game.Game, P = game.Person } into g
select new {
Person = g.Key.P,
Game = g.Key.G,
Score = g.Aggregate((curmin, x) => (curmin == null || (x.EventTime) < curmin.EventTime ? x : curmin)).Score
};
foreach (var item in q)
{
Console.WriteLine("{0}, {1}, {2}", item.Game, item.Person, item.Score);
}
正如@Rawling指出的那样,如果你拥有大量数据集,那么获取scoce可能会非常昂贵。因此,有效地执行此操作可能会节省大量时间来获得所需的输出。
答案 1 :(得分:1)
var dt = DateTime.Now.AddDays(-1);
var results = context.Where(x=>x.EventTime >= dt)
.GroupBy(x=>new {x.Person,x.Game})
.Select(x=>new
{
x.Key.Person,
x.Key.Game,
LatestScore = x.Where(d=>d.EventTime == x.Max(l=>l.EventTime))
.Select(d=>d.Score)
.FirstOrDefault()
});