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

后端 未结 3 1943
借酒劲吻你
借酒劲吻你 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: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 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;
        }
    

提交回复
热议问题