A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Thursday, February 20, 2020

Making a delimited list

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
        List data = (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)
            // Convert the string builder to a string and then strip the first
            // character out of it
            string final = sb.ToString().Substring(delimiter.Length);
        // 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()));

Output of running the above
Gist for .net

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: