Making a delimited list
There are various ways to concatenate values together. A common approach I see is that people will add a delimiter and then the value and loop until they finish. Then they take away the first delimiter. Generally, that's easier coding, prepending a delimiter, than to append the delimiter and not do it for the final element of a list. Or add it and then remove the final delimiter from the resulting string.
Gentle reader, there is a better way. And has been for quite some time but if you weren't looking for it, you might not know it exists. In .NET, it's String.Join
Look at the following code, what would you rather write? The Avoid this block or simply use the libraries?
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text; public class Program { public static void Main() { // generate a list of numbers ListOutput of running the abovedata = (Enumerable.Range(0, 10)).ToList (); string delimiter = ","; // Avoid this, unless you know you need to do it for a specific reason { StringBuilder sb = new StringBuilder(); foreach(var i in data) { sb.Append(delimiter); sb.Append(i); } // Convert the string builder to a string and then strip the first // character out of it string final = sb.ToString().Substring(delimiter.Length); Console.WriteLine(final); } // Make a comma delimited list Console.WriteLine(String.Join(delimiter, data)); // What if we want to do something, like put each element in an XML tag? Console.WriteLine(String.Join(string.Empty, data.Select(x => string.Format(" {0}", x)).ToList())); } }
0,1,2,3,4,5,6,7,8,9 0,1,2,3,4,5,6,7,8,9Gist for .net0 1 2 3 4 5 6 7 8 9
But Bill, I use Python. The syntax changes but the concept remains the same. delimiter.join(data)
. Whatever language you use, there's probably an equivalent method. Look for it and use it. Don't write your own implementation.
Was there a better way to have done this? Let me know.
No comments:
Post a Comment