替代foreach循环和字符串生成器

时间:2016-01-26 14:22:28

标签: c#

我有一个获取实体集合的函数,然后在字符串中添加引号和逗号以更新数据库中的集合。这花费了大量的时间,效率非常低,但我无法想到另一种选择:

IEntityCollection c = Transactions.EvalToEntityCollection<ITransactions>(Store, key, item);

int max = transes.Count <= 750 ? transes.Count : 750;  // DB times out if there are more than 750, so 750 is the limit
int i = 0;
int t = transes.Count;
StringBuilder sb = new StringBuilder();

foreach (ITransactions trans in transes)
{
    sb.Append("'");
    sb.Append(trans.GUID);
    sb.Append("',");
    i++;
    t--;

    if (i == max || t == 0)
    {
        sb.Remove(sb.Length - 1, 1);

        //in here, code updates a bunch of transactions (if <=750 transaction)

        i = 0;
        sb = new StringBuilder();
    }
}

3 个答案:

答案 0 :(得分:3)

或许这样的事情?

var str = String.Join(",", transes.Select(t => string.Format("'{0}'", t.GUID)))

但是,由于您的代码中有评论表明它会超时> 750条记录,因此您需要花费大量时间&#34;可能来自数据库,而不是您的代码。

String.Join是一种非常方便的方法,当您想要将一组内容连接在一起时,因为它会自动为您处理结束(因此您不会使用前导或尾随分隔符)。

答案 1 :(得分:1)

似乎你想这样做:

  1. 将交易编号分组为最多750个实体的批次
  2. 将所有这些交易号码放在一个由逗号分隔的字符串中并用单引号括起来
  3. 如果是,那么这里是构建批次的代码:

    const int batchSize = 750;
    List<List<Transaction>> batches =
        transes
        .Select((transaction, index) => new { transaction, index })
        .GroupBy(indexedTransaction => indexedTransaction.index / batchSize)
        .Select(group => group.Select(indexedTransaction => indexedTransaction.transaction).ToList())
        .ToList();
    foreach (var batch in batches)
    {
        // batch here is List<Transaction>, not just the GUIDs
        var guids = string.Join(", ", batch.Select(transaction => "'" + transaction.GUID + "'"));
        // process transaction or guids here
    }
    

答案 2 :(得分:0)

字符串构建器很有效。这样做750次(这是你的最大值)肯定不会比任何可用的技术花费更长的时间。

请注释掉StringBuilder部分并运行项目

sb.Append("'");
sb.Append("',");

我敢打赌,完成时间将完全相同。