Join List <string> Together with Commas Plus "and" for the last item

I know that I can find a way out, but I wonder if there is a more concise solution. Always String.Join(", ", lList) and lList.Aggregate((a, b) => a + ", " + b); but I want to add an exception for the latter in order to have ", and " as my connection string. Does Aggregate() any index value that I can use? Thanks.

+7
list c #
source share
4 answers

You can do it

 string finalString = String.Join(", ", myList.ToArray(), 0, myList.Count - 1) + ", and " + myList.LastOrDefault(); 
+15
source share

I use the following extension method (with some code protection):

 public static string OxbridgeAnd(this IEnumerable<String> collection) { var output = String.Empty; var list = collection.ToList(); if (list.Count > 1) { var delimited = String.Join(", ", list.Take(list.Count - 1)); output = String.Concat(delimited, ", and ", list.LastOrDefault()); } return output; } 

Here is the unit test for it:

  [TestClass] public class GrammarTest { [TestMethod] public void TestThatResultContainsAnAnd() { var test = new List<String> { "Manchester", "Chester", "Bolton" }; var oxbridgeAnd = test.OxbridgeAnd(); Assert.IsTrue( oxbridgeAnd.Contains(", and")); } } 
+8
source share

Here is a solution that works with empty lists and a list with one item in them:

FROM#

 return list.Count() > 1 ? string.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last() : list.FirstOrDefault(); 

Vb

 Return If(list.Count() > 1, String.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last(), list.FirstOrDefault()) 
+5
source share

This version lists the values ​​once and works with any number of values:

 public static string JoinAnd<T>(string separator, string sepLast, IEnumerable<T> values) { var sb = new StringBuilder(); var enumerator = values.GetEnumerator(); if (enumerator.MoveNext()) { sb.Append(enumerator.Current); } object obj = null; if (enumerator.MoveNext()) { obj = enumerator.Current; } while (enumerator.MoveNext()) { sb.Append(separator); sb.Append(obj); obj = enumerator.Current; } if (obj != null) { sb.Append(sepLast); sb.Append(obj); } return sb.ToString(); } 
+2
source share

All Articles