Skip to content

Instantly share code, notes, and snippets.

@billinkc
Last active February 20, 2020 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billinkc/3678a94244d8a7f86bc567aed33e0aba to your computer and use it in GitHub Desktop.
Save billinkc/3678a94244d8a7f86bc567aed33e0aba to your computer and use it in GitHub Desktop.
Code to accompany a blog post about building delimited lists in .net
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<int> data = (Enumerable.Range(0, 10)).ToList<int>();
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("<col>{0}</col>", x)).ToList()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment