Comma separated list with “and” in place of the last comma

后端 未结 3 1972
借酒劲吻你
借酒劲吻你 2020-12-30 03:20

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

string.Join(\", \", someStringArray)

will result in

3条回答
  •  长情又很酷
    2020-12-30 03:53

    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.

提交回复
热议问题