Formating a list of items into a sentence with commas and the ampersand.
December 9th, 2009
Description:
I need to link an list of (string) items into a sentence at runtime. Here’s a short and simple method to handle the commas and ampersand.
Code:
static string JoinPhrases(Listphrases) { StringBuilder str = new StringBuilder(); for(int i = 0, j = 1; i < phrases.Count ; i++, j++) { str.Append(phrases[i]); if ( j + 1 < phrases.Count ) str.Append(", "); else if ( j + 1 == phrases.Count ) str.Append(" & "); else if ( j == phrases.Count ) str.Append("."); } return str.ToString(); }
Usage:
Listonly = new List { "Solo" }; List boolean = new List { "True", "False" }; List numbers = new List { "One", "Two", "Three" }; List names = new List { "Fred", "Barney", "Wilma", "Betty" }; List months = new List { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; Console.WriteLine("Join Only:" + Environment.NewLine + JoinPhrases(only) + Environment.NewLine); Console.WriteLine("Join Boolean:" + Environment.NewLine + JoinPhrases(boolean) + Environment.NewLine); Console.WriteLine("Join Names:" + Environment.NewLine + JoinPhrases(names) + Environment.NewLine); Console.WriteLine("Join Numbers:" + Environment.NewLine + JoinPhrases(numbers) + Environment.NewLine); Console.WriteLine("Join Months:" + Environment.NewLine + JoinPhrases(months) + Environment.NewLine); Console.ReadLine();
Notes:
Looking at this code, I have to wonder if there is a way to oneline it with a LINQ query. Hmm...
