我有一个大约4500行的数据集。我将它传递给Web服务,但在性能问题和超时之后,我们希望能够一次传递100个这样的行。
如何在c#中实现?
我是否需要将数据集拆分为100个表,然后循环遍历表格,或者是否有更简单的方法一次发送100行集合?
答案 0 :(得分:2)
您可以使用Linq,特别是Take和CopyToDataTable扩展名。
示例:
DataSet ds = new DataSet();
DataTable dt = ds.Tables["YOURDATATABLE"];
IEnumerable<DataRow> firstHundred = dt.AsEnumerable().Take(100);
// create datatable from query
DataTable boundTable = firstHundred.CopyToDataTable<DataRow>();
//call your web service with 1st hundred
//
IEnumerable<DataRow> nextHundred = dt.AsEnumerable().Skip(100).Take(100);
// and so on
boundTable = nextHundred.CopyToDataTable<DataRow>();
//call your web service with 1st hundred
//
简单for和Linq的示例考虑到你有4,500行,并希望按100组进行分块:
DataSet ds = new DataSet();
DataTable dt = ds.Tables["YOURDATATABLE"];
IEnumerable<DataRow> firstHundred = dt.AsEnumerable().Take(100);
// create datatable from query
DataTable boundTable = firstHundred.CopyToDataTable<DataRow>();
//call your web service with 1st hundred
//
int skipCount = 0;
for (int i = 1; i <= 45; i++)
{
skipCount += 100;
IEnumerable<DataRow> nextHundred = dt.AsEnumerable().Skip(skipCount).Take(100);
// create datatable from query
DataTable boundTable = nextHundred.CopyToDataTable<DataRow>();
// call web service with next hundred and so on
}
答案 1 :(得分:1)
private IEnumerable<IEnumerable<DataRow>> GetChunks(DataTable table, int size)
{
List<DataRow> chunk = new List<DataRow>(size);
foreach (DataRow row in table.Rows)
{
chunk.Add(row);
if (chunk.Count == size)
{
yield return chunk;
chunk = new List<DataRow>(size);
}
}
if(chunk.Any()) yield return chunk;
}
//....
DataTable table = dataSet.Tables[yourTable];
var chunks = GetChunks(table, 100);
foreach (IEnumerable<DataRow> chunk in chunks)
SendChunk(chunk); // <-- Send your chunk of DataRow to webservice
您还可以尝试并行发送数据:
// This would replace the above last two lines
Parallel.ForEach(chunks, chunk => SendChunk(chunk));
虽然我不推荐这样做,因为SendChunk
是I / O操作。
相反,尝试将代码转换为async
,您可以获得更好的结果:
// Will execute all tasks at the same time
// SendChunk should return a Task
await Task.WhenAll(chunks.Select(chunk => SendChunk(chunk)).ToArray());