更新:这是一个类似的问题
假设我有一个里面DataTable
有几千个DataRows
。
我想将表分解成小行进行处理。
我认为 C#3 改进的数据处理能力可能会有所帮助。
这是我到目前为止的骨架:
DataTable Table = GetTonsOfData();
// Chunks should be any IEnumerable<Chunk> type
var Chunks = ChunkifyTableIntoSmallerChunksSomehow; // ** help here! **
foreach(var Chunk in Chunks)
{
// Chunk should be any IEnumerable<DataRow> type
ProcessChunk(Chunk);
}
关于应该替换什么的任何建议ChunkifyTableIntoSmallerChunksSomehow
?
我真的很感兴趣有人会如何通过访问 C#3 工具来做到这一点。如果试图应用这些工具是不合适的,请解释!
更新 3(修改了分块,因为我真的想要表,而不是 ienumerables;使用扩展方法——感谢 Jacob):
最终实现:
处理分块的扩展方法:
public static class HarenExtensions
{
public static IEnumerable<DataTable> Chunkify(this DataTable table, int chunkSize)
{
for (int i = 0; i < table.Rows.Count; i += chunkSize)
{
DataTable Chunk = table.Clone();
foreach (DataRow Row in table.Select().Skip(i).Take(chunkSize))
{
Chunk.ImportRow(Row);
}
yield return Chunk;
}
}
}
该扩展方法的示例使用者,带有来自临时测试的示例输出:
class Program
{
static void Main(string[] args)
{
DataTable Table = GetTonsOfData();
foreach (DataTable Chunk in Table.Chunkify(100))
{
Console.WriteLine("{0} - {1}", Chunk.Rows[0][0], Chunk.Rows[Chunk.Rows.Count - 1][0]);
}
Console.ReadLine();
}
static DataTable GetTonsOfData()
{
DataTable Table = new DataTable();
Table.Columns.Add(new DataColumn());
for (int i = 0; i < 1000; i++)
{
DataRow Row = Table.NewRow();
Row[0] = i;
Table.Rows.Add(Row);
}
return Table;
}
}