Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,

I would like to get a comma separated list. I have two approaches.
First one is normal For loop and second one is String.Join() Method.
Considering the performance which will be the best approach.

C#
StringBuilder KeyTmsList = new StringBuilder();
for (int i = 0; i < dsKeytms.Tables[0].Rows.Count; i++)
 {
   KeyTmsList = KeyTmsList.Append("'" + dsKeytms.Tables[0].Rows[i]["KEY_TMS"].ToString() + "'" + ",");
 }
  KeyTmsList = KeyTmsList.Remove(KeyTmsList.Length - 1, 1);



C#
string KeyTmsList = string.Join(",", dsKeytms.Tables[0].AsEnumerable().Select(r => r.Field<string>("KEY_TMS")).ToArray());
Posted

I think string.join() is the best option.
 
Share this answer
 
Comments
jinesh sam 13-Apr-15 5:31am    
Hi Samit,
Can you give any valid reason for your selection.
samitrpatel 13-Apr-15 6:09am    
You should use string.Join() because:

1) it's much more readable, maintainable and easy on the eyes.

2) it uses a StringBuilder internally already, so it's very efficient ( you can confirm yourself using Reflector).

string.Join() uses a StringBuilder for the general case of an IEnumerable<t> input. If you already have an array on the other hand it uses some voodoo magic (including FastAllocateString() and UnSafeCharBuffer) to be even faster.
jinesh sam 13-Apr-15 6:56am    
Thanks:)
samitrpatel 13-Apr-15 7:55am    
always welcome.
A comparison of 'StringBuilder and 'Join is difficult here because you are using different methods of "composing" the contents of your Tables[0] (its Rows) into an enumerable form for manipulation: in the second example you are using Linq instead of a for-loop.

So, in some ways you are really asking about comparing using Linq to using a 'for-loop.

There is a detailed discussion of using 'Join vs. 'StringBuilder here: [^] which you might find useful.

Also see the discussion and timing results here: [^].

My reading of the above discussions suggests that 'Join and 'StringBuilder are about equally performant, but I believe that for your case you'd have to do some timing.

The special case of 'Join using 'StringBuilder internally appears to be true only under these conditions:

1. .NET 4.0 or later

2. the argument to 'Join is an IEnumerable<string>

However, when the arguments to 'Join is an Array, 'Join uses "FastAllocateString() and UnSafeCharBuffer)" ... see the second link above for the source of this comment.
 
Share this answer
 
Comments
Maciej Los 13-Apr-15 9:11am    
Nice explained ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900