重新格式化字符串以逗号分隔和格式化 [英] Reformat string to be comma separated and formatted

查看:55
本文介绍了重新格式化字符串以逗号分隔和格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表...

I have a list of strings...

var strings = new List<String>() { "a", "b", "c" };

我想以不同的格式输出它们,如下所示:

I want to output them in a different format, like this:

'a','b','c'

'a','b','c'

我试过了:

string.Join("','",strings );

String.Join(",", String.Format("'{0}'",strings )

推荐答案

您的第一次尝试应该可行,但是您需要使用 "'" 前缀和后缀.

Your first attempt should work, but you need to prefix and suffix the overall result with "'".

或者,你可以这样做:

var strings = new List<string>() { "a", "b", "c" }
                  .Select(x => string.Format("'{0}'", x));

var result = string.Join(",", strings);

另一种选择是使用 StringBuilder 代替,

Another option is to use a StringBuilder instead,

var strings = new List<string>() { "a", "b", "c" };
var builder = new StringBuilder();

foreach (var s in strings)
{
    builder.AppendFormat(",'{0}'", s);
}

var result = builder.ToString().Trim(",");

在这种情况下,我建议使用 LINQ 方法,因为它很简单,但如果您的实际问题更复杂,不要排除 StringBuilder,因为它可以显示格式化的意图每个单独的项目更干净.

In this case I'd recommend the LINQ approach for it's simplicity, but don't rule out the StringBuilder if your real problem is more complex, as it can show the intent of the formatting of each individual item more cleanly.

一种混合方法,您使用 StringBuilder 格式化每个项目的内容,然后使用 LINQ 构建逗号分隔的列表,这种方法可以很好地工作.

A hybrid approach where you format the content of each item using a StringBuilder, then build the comma-separated list using LINQ afterwards, could work well.

这篇关于重新格式化字符串以逗号分隔和格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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