Last active
February 20, 2020 18:39
-
-
Save billinkc/3678a94244d8a7f86bc567aed33e0aba to your computer and use it in GitHub Desktop.
Code to accompany a blog post about building delimited lists in .net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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