简体   繁体   English

Linq查询来做分组和最小

[英]Linq query to do group by and min

I have a datastructure as shown below. 我有如下所示的数据结构。 For each (Person, Game) pairs, I need to find the lastest score in the past 24 hours. 对于每对(人,游戏),我需要查找过去24小时内的最新得分。 Is it possible to do that in LINQ? 是否可以在LINQ中做到这一点? Something like (Person, Game, LatestScore) 像(人,游戏,最新分数)

+----------------+-----------------+---------------+-+------------+
| Person         |  Game           | Score         |EventTime     |
+-----------------------------------------------------------------+
|                |                 |               |              |
|                |                 |               |              |
+----------------+-----------------+---------------+--------------+

Any hints would be very helpful. 任何提示将非常有帮助。

Assuming you have a class like this: 假设您有这样的课程:

    class GameInfo
    {

        public DateTime EventTime { get; set; }
        public String Game { get; set; }
        public String Person { get; set; }
        public double Score { get; set; }
    }

You could do: 您可以这样做:

        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);
        }

As @Rawling pointed out, getting the scoce can be quite costly if you have lage data sets. 正如@Rawling所指出的那样,如果您拥有大量数据集,那么获得评分可能会非常昂贵。 So doing that efficiently might save alot of time in getting the desired output. 因此,高效地执行此操作可能会节省大量时间来获得所需的输出。

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()
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM