Skip to content

Instantly share code, notes, and snippets.

@billinkc
Last active Feb 20, 2020
Embed
What would you like to do?
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