The first thing I think to do is to just get the Length or the Count() of the list and increment your own counter and put in the "and" before the last one.
You could do it in a regular "for" loop.
I might do it something like this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace DW_411840_CS_CON
{
class Program
{
static void Main(string[] args)
{
List<string> lst_strSevenDwarfs = new List<string>
{ "Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey" };
string strSevenDwarfs = // technique 1 (keep the last comma)
string.Join(", ",
lst_strSevenDwarfs.Except(
new List<string>{lst_strSevenDwarfs.Last()})
.Union(new List<string>{"and " + lst_strSevenDwarfs.Last()})
.ToArray());
Console.WriteLine(strSevenDwarfs);
strSevenDwarfs = // technique 2 (eliminate the last comma)
string.Join(", ",
lst_strSevenDwarfs.Except(
new List<string> { lst_strSevenDwarfs.Last() })
.ToArray())
+ " and " + lst_strSevenDwarfs.Last();
Console.WriteLine(strSevenDwarfs);
}
}
} thines01
Postaholic
Team Colleague
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402