dlidstrom/Snittlistan — Issue #92: Senaste 20 serierna
Author: dlidstrom
Created: 2011-11-18 13:46:48+00:00
State: open

Från Ryan Heath:

using System;
using System.Linq;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
using Raven.Client.Linq;

namespace ConsoleApplication
{
class Program
{
class PlayerPins
{
public string Player { get; set; }
public DateTime Date { get; set; }
public int Pins { get; set; }
}

class Pins_ByMatchDate : AbstractIndexCreationTask
{
public Pins_ByMatchDate()
{
Map = pins => from pin in pins
select new
{
pin.Player,
pin.Date,
pin.Pins
};

Reduce = maps => from map in maps
group map by map.Player into grouped
select new
{
Player = grouped.Key,
grouped.OrderByDescending(x => x.Date).Take(3).First().Date,
Pins = grouped.OrderByDescending(x => x.Date).Take(3).Average(x => x.Pins),
};
}

public class Result
{
public string Player { get; set; }
public DateTime Date { get; set; }
public double Pins { get; set; }
}
}

static void Main()
{
var playerPins = new[]
{
new PlayerPins {Player = "John", Date = new DateTime(2011, 10, 11), Pins = 200},
new PlayerPins {Player = "John", Date = new DateTime(2011, 11, 11), Pins = 250},
new PlayerPins {Player = "John", Date = new DateTime(2011, 11, 12), Pins = 240},
new PlayerPins {Player = "John", Date = new DateTime(2011, 11, 13), Pins = 260},
new PlayerPins {Player = "John", Date = new DateTime(2011, 11, 14), Pins = 270},
new PlayerPins {Player = "Pete", Date = new DateTime(2010, 11, 11), Pins = 300},
new PlayerPins {Player = "Pete", Date = new DateTime(2011, 11, 11), Pins = 300},
new PlayerPins {Player = "Pete", Date = new DateTime(2011, 11, 12), Pins = 300},
new PlayerPins {Player = "Pete", Date = new DateTime(2011, 11, 13), Pins = 300},
new PlayerPins {Player = "Kara", Date = new DateTime(2011, 10, 11), Pins = 100},
new PlayerPins {Player = "Kara", Date = new DateTime(2011, 10, 12), Pins = 200},
new PlayerPins {Player = "Kara", Date = new DateTime(2011, 10, 13), Pins = 300}
};

using (var store = new EmbeddableDocumentStore { RunInMemory = true })
{
store.Initialize();

IndexCreation.CreateIndexes(typeof(Pins_ByMatchDate).Assembly, store);

using (var session = store.OpenSession())
{
foreach(var playerPin in playerPins)
{
session.Store(playerPin);
}

session.SaveChanges();
}

using (var session = store.OpenSession())
{
var lastAveragePins = session.Query()
.AsProjection()
.Customize(x => x.WaitForNonStaleResults());

foreach (var pins in lastAveragePins)
{
Console.WriteLine("{0} {1:yyyy/MM/dd} {2}", pins.Player, pins.Date, pins.Pins);
}

// expect to see
// John 2011-11-14 256.666666666667
// Pete 2011-11-13 300
// Kara 2011-10-13 200
}
}
}
}
}