通过linq查询表中的每个月记录
我有一个名为testable的数据表,它有两列id(主键,int)和time(datetime)。我想计算表中每个特定月份的记录数。例如,表中有5行通过linq查询表中的每个月记录,linq,Linq,我有一个名为testable的数据表,它有两列id(主键,int)和time(datetime)。我想计算表中每个特定月份的记录数。例如,表中有5行 Id datetime(d/m/y) 1 12/3/2011 2 15/3/2011 3 4/4/2011 4 1/8/2011 5 19/12/2011 如何编写Linq查询以这样查询出记录 Id datetime count 1. 1/2011 0 2. 2/201
Id datetime(d/m/y)
1 12/3/2011
2 15/3/2011
3 4/4/2011
4 1/8/2011
5 19/12/2011
如何编写Linq查询以这样查询出记录
Id datetime count
1. 1/2011 0
2. 2/2011 0
3. 3/2011 2
4. 4/2011 1
5. 5/2011 0
6. 6/2011 0
7. 7/2011 0
8. 8/2011 1
9. 9/2011 0
10. 10/2011 0
11. 11/2011 0
12. 12/2011 1
var query = from c in testtable.AsEnumerable()
group c by new
{
years = Convert.ToDateTime(c.Field<string>("Posted")).Year,
months = Convert.ToDateTime(c.Field<string>("Posted")).Month
}
into d
orderby d.Key.years,d.Key.months
select new
{
Date = String.Format("{0}/{1}",d.Key.months,d.Key.years),
Count = d.Count()
};
我写了一个这样的查询语句
Id datetime count
1. 1/2011 0
2. 2/2011 0
3. 3/2011 2
4. 4/2011 1
5. 5/2011 0
6. 6/2011 0
7. 7/2011 0
8. 8/2011 1
9. 9/2011 0
10. 10/2011 0
11. 11/2011 0
12. 12/2011 1
var query = from c in testtable.AsEnumerable()
group c by new
{
years = Convert.ToDateTime(c.Field<string>("Posted")).Year,
months = Convert.ToDateTime(c.Field<string>("Posted")).Month
}
into d
orderby d.Key.years,d.Key.months
select new
{
Date = String.Format("{0}/{1}",d.Key.months,d.Key.years),
Count = d.Count()
};
var query=来自testtable.AsEnumerable()中的c
c组由纽约
{
年=转换为当前时间(c.字段(“已过账”)。年,
月份=转换为.ToDateTime(c.字段(“已过账”)。月份
}
进入d
按d.Key.年,d.Key.月订购
选择新的
{
Date=String.Format(“{0}/{1}”,d.Key.months,d.Key.years),
Count=d.Count()
};
但是它只查询出3/4/8/12月份,不能查询出其他月份的记录。
有人可以帮忙吗?您需要生成一个所有日期的序列,然后将现有查询与该序列连接起来
var allMonths = Enumerable.Range(1, 12)
.Select(i => String.Format("{0}/{1}", i, "2011"));
var query = new[]
{
new{ Date= "3/2011" , Count = 2},
new{ Date= "4/2011" , Count = 1},
new{ Date= "8/2011" , Count = 1},
new{ Date= "12/2011", Count = 1},
};
var query2 = from month in allMonths
join date in query on month equals date.Date into g
from date in g.DefaultIfEmpty()
select new
{
Date = month,
Count = (date == null) ? 0 : date.Count
};
foreach (var q in query2)
{
Console.WriteLine(q);
}
但是您向我们展示的数据只包含3/4/8/12中的行,因此工作正常。