I want to create a comma separated list in C# with the word \"and\" as last delimiter.
string.Join(\", \", someStringArray)
will result in
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.
Is there a simple way to achieve it with Linq and without using loops?
Not possible without loop. For loop will work best. LINQ queries will use multiple loops.
string Combine (IEnumerable<string> list)
{
bool start = true;
var last = string.Empty;
String str = string.Empty;
foreach(var item in list)
{
if ( !start)
{
str = str + " , " + item;
last = item;
}
else
{
str = item;
start = false;
}
}
if (!string.IsNullOrWhiteSpace(last))
{
str = str.Replace( " , " + last, " and " + last);
}
return str;
}
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.