【问题标题】:Pass subsets of datatable to SQL Server将数据表的子集传递给 SQL Server
【发布时间】:2011-01-15 07:08:47
【问题描述】:

我试图弄清楚如何分解我的数据表并将其(作为 UDT)发送到 sql server)。因此,如果我的数据表中有 100,000 个,我希望能够将其分解为 10,000 个块以发送到我的 sql 服务器。我只是不确定如何将 100,000 的数据表分解成这 10,000k 块?

任何建议将不胜感激。

所以如果我使用这样的东西:

var results = (from myRow in myDataTable.AsEnumerable()
              select myRow).take(10000);

不确定如何确保从数据表中抓取下一组 10,000 行并确保不发送重复并获取所有行?

【问题讨论】:

  • @BrokenGlass 你能进一步解释一下你的意思吗?

标签: c# c#-4.0


【解决方案1】:

只需为自己编写一个简单的方法,将任何集合变成指定大小的块:

/// <summary>Splits a collection into chunks of equal size. The last chunk may be smaller than chunkSize, but all chunks, if any, will contain at least one element.</summary>
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunkSize)
{
    if (chunkSize <= 0)
        throw new ArgumentException("chunkSize must be greater than zero.", "chunkSize");
    return chunkIterator(source, chunkSize);
}
private static IEnumerable<IEnumerable<T>> chunkIterator<T>(IEnumerable<T> source, int chunkSize)
{
    var list = new List<T>();
    foreach (var elem in source)
    {
        list.Add(elem);
        if (list.Count == chunkSize)
        {
            yield return list;
            list = new List<T>();
        }
    }
    if (list.Count > 0)
        yield return list;
}

然后你可以简单地使用它,例如:

foreach (var chunk in myDataTable.AsEnumerable().Chunk(10000))
{
    // Process the chunk
}

【讨论】:

  • 谢谢@Timwi!我会试一试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
相关资源
最近更新 更多