Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to a foreach loop and a string builder

Tags:

c#

I have a function that gets a collection of entities, and then appends quotes and commas to the string to update the collection in the DB. This is taking an insane amount of time, it's very inefficient, but I can't think of an alternative:

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();
    }
}
like image 980
sharpiepen Avatar asked Jan 26 '16 14:01

sharpiepen


1 Answers

Something like this perhaps?

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

But since you have the comment in your code that it times out with > 750 records, your "insane amount of time" might be from the database, not your code.

String.Join is a really handy method when you want to concatenate a list of stuff together because it automatically handles the ends for you (so you don't end up with leading or trailing delimiters).

like image 200
Matt Burland Avatar answered Sep 20 '22 20:09

Matt Burland