有什么简单的方法可以将datatable切成一个范围,并对一个范围进行计数汇总吗?
假设我有下面的数据表
Date Count
5/9/2016 5
5/10/2016 1
5/11/2016 2
5/12/2016 4
5/13/2016 3
5/14/2016 2
5/15/2016 1
5/16/2016 4如果我把它切成2,它就会使2行..something像
DateRange Count
5/9/2016-5/10/2016 6
5/11/2016-5/12/2016 6
5/13/2016-5/14/2016 5
5/15/2016-5/16/2016 5如果我把它切成3,它就会像3行..something一样
DateRange Count
5/9/2016-5/11/2016 8
5/12/2016-5/14/2016 9
5/15/2016-5/16/2016 5我试图在一个日期范围的asp:图表(StackedColumn)图表中显示我的数据。日期范围从7,15,30,60,90,150,365天不等-- ..almost每天都有一些数据条目,还有一个自定义日期控件来选择日期。假设用户选择的日期范围为200天,200天为他们的遗嘱200记录。现在是否有任何方法来显示数据并在图表中显示,.Currently,我试图按月做,但我知道有一个自定义的日期范围,所以我需要一个不同的解决办法,任何帮助它。
public DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("R", typeof(int));
table.Columns.Add("C", typeof(int));
// Here we add five DataRows.
for (int i = 0; i <= dayschunk; i++)
{
table.Rows.Add(DateTime.Now.Date.AddDays(-i).ToString("MMM-dd"), new Random().Next(0, 99), new Random().Next(0, 99));
}
var results = from row in table.AsEnumerable()
group row by new { Date = row.Field<DateTime>("Date").Month } into rowgroup
select new
{
rowgroup.Key.Date,
Remidiated = rowgroup.Sum(r => r.Field<int>("R")),
Stucked = rowgroup.Sum(r => r.Field<int>("C"))
};
DataTable filtered = new DataTable();
filtered.Columns.Add("DateRange", typeof(int));
filtered.Columns.Add("R", typeof(int));
filtered.Columns.Add("C", typeof(int));
foreach (var item in results)
{
table.Rows.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.Date), item.Remidiated, item.Stucked);
}
//table.Rows.Add(2,new DateTime(2016, 05, 02), 50, 50);
//table.Rows.Add(2,new DateTime(2016, 05, 07), 3, 4);
//table.Rows.Add(2,new DateTime(2016, 05, 05), 16, 10);
return filtered;
}发布于 2016-05-10 03:14:26
您可以使用Select重载来传递索引并创建具有给定大小的块。
DataTable result = new DataTable();
result.Columns.Add("DateRange", typeof(string));
result.Columns.Add("Count", typeof(int));
int chunk = 2;
result = table.AsEnumerable()
.Select((row,i) => new {gid= i/chunk, row})
.GroupBy(x=>x.gid)
.Select(x=>
{
var row= result.NewRow();
row["DateRange"] = string.Format("{0}-{1}", x.First().row.Field<DateTime>("Date"), x.Last().row.Field<DateTime>("Date"));
row["Count"]= x.Sum(r=>r.row.Field<int>("R"));
return row;
}).CopyToDataTable<DataRow>();检查这个Example
注意:我还没有应用输出格式,但您可以轻松地实现,我将把它留给您。
https://stackoverflow.com/questions/37128429
复制相似问题