我有一个包含以下字段的表:
示例:
行动|日期时间
等。
我需要按小时对这些进行分组,以便每小时点击一次并按小时打开。
我怎么办? 感谢答案 0 :(得分:4)
var poo = new[]
{
new
{
Type = "Click",
Time = DateTime.Parse("March 12, 2010 3:00AM")
},
new
{
Type = "Click",
Time = DateTime.Parse("March 12, 2010 3:12AM")
},
new
{
Type = "Open",
Time = DateTime.Parse("March 12, 2010 3:34AM")
},
new
{
Type = "Click",
Time = DateTime.Parse("March 12, 2010 4:12AM")
},
new
{
Type = "Click",
Time = DateTime.Parse("March 13, 2010 1:12PM")
}
};
var result = from s in poo
group s by new {s.Type, s.Time.Hour} into p
select new
{
p.Key.Type,
p.Key.Hour,
Count = p.Count()
};
foreach (var s in result)
{
Console.WriteLine(s.Count + " - " + s.Type + " - " + s.Hour);
}
输出:
2 - Click - 3
1 - Open - 3
1 - Click - 4
1 - Click - 13
那你在寻找什么?
答案 1 :(得分:1)
你可以使用lambda
这样做 var data = new[]
{
new { Actn = "click", tm = "3/12/2010 3:00AM" },
new { Actn = "click" , tm = "3/12/2010 3:12AM"},
new { Actn = "open" , tm = "3/12/2010 3:34AM"},
new { Actn = "click" , tm = "3/12/2010 4:12AM"},
new { Actn = "click" , tm = "3/13/2010 1:12PM"}
};
var groupby = data.GroupBy(r => new { Convert.ToDateTime(r.tm).Hour, r.Actn });
foreach (var group in groupby)
{
Console.WriteLine("{0} = {1}", group.Key, group.Count());
}
答案 2 :(得分:0)
我这样解决了:
List<MySummary> summary =
entries.Select(i => new { i, dt = i.Date }).GroupBy(
@t => new { date = @t.dt.Date, time = @t.dt.Hour }, @t => @t.i).Select(
g =>
new MySummary()
{
Date = g.Key.date.AddHours(g.Key.time),
Opens = g.Count(x => x.Type == "Open"),
Clicks = g.Count(x => x.Type == "Click")
}).ToList();
如果你们认为这是不正确的,请告诉我。但是从它的外观来看......它能获得正确的数据。
型号:
public class MySummary
{
public DateTime Date { get; set; }
public int Opens { get; set; }
public int Clicks { get; set; }
}