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

后端 未结 3 1944
借酒劲吻你
借酒劲吻你 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:40

    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.

    0 讨论(0)
  • 2020-12-30 03:41

    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;
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题