我有如下用法集合,需要如下输出:
这是我的用法类:
public class Usage
{
public Usage() {}
public string Alias { get; set; }
public int ActivityCount { get; set; }
public DateTime HitDate { get; set; }
}
这是我的代码:
我想首先将集合分组到用户中,对于每个用户,我想获得每天的点击次数,如下面的EXPECTED输出所示。请注意,日期时间a和d在同一天是不同的时间,因此需要将它们组合在一起。
这将用于绘制命中与日期的条形图,即每天的命中数
执行此操作时,我无法将别名字段数据保存到我的第二级分组中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NullOperator
{
class Program
{
static void Main(string[] args)
{
var a = new DateTime(2015, 10, 23, 12, 05, 06);
var b = new DateTime(2015, 10, 24, 12, 05, 06);
var c = new DateTime(2015, 10, 25, 12, 05, 06);
var d = new DateTime(2015, 10, 23, 14, 05, 06);
var usages = new List<Usage>
{
new Usage{Alias = "A ",HitDate = a},
new Usage{Alias = "A ",HitDate = a},
new Usage{Alias = "A ",HitDate = d},
new Usage{Alias = "A ",HitDate = b},
new Usage{Alias = "A ",HitDate = b},
new Usage{Alias = "A ",HitDate = b},
new Usage{Alias = "A ",HitDate = c},
new Usage{Alias = "B ",HitDate = a},
new Usage{Alias = "B ",HitDate = b},
new Usage{Alias = "B ",HitDate = b},
new Usage{Alias = "B ",HitDate = c},
new Usage{Alias = "B ",HitDate = c},
new Usage{Alias = "B ",HitDate = c},
new Usage{Alias = "C ",HitDate = a},
new Usage{Alias = "C ",HitDate = a},
new Usage{Alias = "C ",HitDate = a},
new Usage{Alias = "C ",HitDate = c},
new Usage{Alias = "C ",HitDate = c},
new Usage{Alias = "C ",HitDate = c},
};
var g = usages.GroupBy(r => r.Alias);
foreach (var u in g)
{
var x = u.GroupBy(r => r.HitDate.Day).Select(gr=>new
{
HitDate=gr.Key,
Count=gr.Count()
});
foreach (var m in x)
{
Console.WriteLine(m.HitDate + " " +m.Count);
}
}
Console.Read();
}
}
//预期输出
Alias : HitDate.Date : hitcount
// A - 23/10/2015 - 3
// A - 24/10/2015 - 3
// A - 25/10/2015 - 1
// B - 23/10/2015 - 1
// B - 24/10/2015 - 2
// B - 25/10/2015 - 3
// C - 23/10/2015 - 3
// C - 24/10/2015- 0
// C - 25/10/2015 - 3
获得的输出:
23 3
24 3
25 1
23 1
24 2
25 3
23 3
25 3
正如您所看到的,分组是正常的,但是整个Date和Alias等信息会丢失,并且无法在嵌套循环的代码中检索它们。
对此有何建议?关于如何获得所需的输出?
答案 0 :(得分:2)
基本上这里有两个问题:
Day
分组,而不是Date
,我怀疑您要做实际上,您可以通过一次性按别名和日期分组来更简单地执行此操作:
var query = usages.GroupBy(r => new { r.Alias, r.HitDate.Date },
(key, elements) => new { key.Alias,
key.Date,
Count = elements.Count() })
.OrderBy(x => x.Alias)
.ThenBy(x => x.Date);
foreach (var item in query)
{
Console.WriteLine("{0} {1} {2}", item.Alias, item.Date, item.Count);
}
答案 1 :(得分:0)
您也可以在select语句中选择该值。
var g = usages.GroupBy(r => r.Alias);
foreach (var u in g)
{
var x = u.GroupBy(r => r.HitDate.Day)
.Select(gr => new {
Alias=u.Alias,
HitDate=gr.Key,
Count=gr.Count()
});
foreach (var m in x)
{
Console.WriteLine(m.HitDate + " " + m.Count);
}
}