Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated list with "and" in place of the last comma

Tags:

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?

like image 911
bytecode77 Avatar asked Jan 02 '13 14:01

bytecode77


People also ask

What is a comma-separated list example?

For example, C{:,1} is a comma-separated list if C has more than one row. A comma-separated list is produced for a structure array when you access one field from multiple structure elements at a time.


2 Answers

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.

like image 138
Wouter de Kort Avatar answered Nov 11 '22 21:11

Wouter de Kort


One possible solution:

var items = someStringArray; // someStringArray.ToList() if not a ICollection<>
var s = string.Join(", ", items.Take(items.Count() - 1)) +
        (items.Count() > 1 ? " and " : "") + items.LastOrDefault();

Note that this statement can iterate someStringArray multiple times if it doesn't implement ICollection<string> (lists and arrays implement it). If so, create a list with your collection and perform the query on that.

like image 35
digEmAll Avatar answered Nov 11 '22 20:11

digEmAll