用“和"逗号分隔的列表代替最后一个逗号 [英] Comma separated list with "and" in place of the last comma

查看:77
本文介绍了用“和"逗号分隔的列表代替最后一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C#创建一个逗号分隔的列表,并以单词"and"作为最后一个定界符.

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

string.Join(", ", someStringArray)

将导致这样的字符串

Apple, Banana, Pear

但是我希望它看起来像这样:

but instead I want it to look like this:

Apple, Banana and Pear

有没有一种简单的方法可以使用Linq和使用循环来实现它?

Is there a simple way to achieve it with Linq and without using loops?

推荐答案

您可以对除最后一项以外的所有项目进行Join,然后手动添加最后一项:

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.

这篇关于用“和"逗号分隔的列表代替最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆