C# – Create Comma Separated List with ‘and’ Before the Last Item

c++linqliststring

I want to create a comma separated list in C# with the word "and" as last delimiter.

string.Join(", ", someStringArray)

will result in a string like this

Apple, Banana, Pear

but instead I want it to look like this:

Apple, Banana and Pear

Is there a simple way to achieve it with Linq and without using loops?

Best Answer

You can do a Join on all items except the last one and then manually add the last item:

using System;
using System.Linq;

namespace Stackoverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            DumpResult(new string[] { });
            DumpResult(new string[] { "Apple" });
            DumpResult(new string[] { "Apple", "Banana" });
            DumpResult(new string[] { "Apple", "Banana", "Pear" });
        }

        private static void DumpResult(string[] someStringArray)
        {
            string result = string.Join(", ", someStringArray.Take(someStringArray.Length - 1)) + (someStringArray.Length <= 1 ? "" : " and ") + someStringArray.LastOrDefault();
            Console.WriteLine(result);
        }
    }
}

As you can see, there is a check on the amount of items and decides if it's necessary to add the 'and' part.

Related Question