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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With