简体   繁体   English

在 C# 中创建一个逗号分隔的字符串

[英]Create a comma-separated strings in C#

I have an object which holds many values, and some of them (not all values from the object) need to be put in a CSV string.我有一个 object ,它包含许多值,其中一些(不是对象的所有值)需要放在CSV字符串中。 My approach was this:我的方法是这样的:

string csvString = o.number + "," + o.id + "," + o.whatever ....

Is there is a better, more elegant way?有没有更好、更优雅的方式?

If you put all your values in an array, at least you can use string.Join .如果您将所有值放在一个数组中,至少您可以使用string.Join

string[] myValues = new string[] { ... };
string csvString = string.Join(",", myValues);

You can also use the overload of string.Join that takes params string as the second parameter like this:您还可以使用string.Join的重载,它将params string作为第二个参数,如下所示:

string csvString = string.Join(",", value1, value2, value3, ...);

Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly.另一种方法是使用 System.Configuration 命名空间/程序集中的 CommaDelimitedStringCollection 类。 It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.它的行为就像一个列表,而且它有一个重写的 ToString 方法,该方法返回一个逗号分隔的字符串。

Pros - More flexible than an array.优点 - 比数组更灵活。

Cons - You can't pass a string containing a comma.缺点 - 您不能传递包含逗号的字符串。

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();

list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");

string s = list.ToString(); //Huey,Dewey,Louie

You can use thestring.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...) .您可以使用string.Join方法来执行类似string.Join(",", o.Number, o.Id, o.whatever, ...)

edit: As digEmAll said, string.Join is faster than StringBuilder.编辑:正如digEmAll所说,string.Join比StringBuilder快。 They use an external implementation for the string.Join.他们对 string.Join 使用外部实现。

Profiling code (of course run in release without debug symbols):分析代码(当然在没有调试符号的发行版中运行):

class Program
{
    static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        string r;
        int iter = 10000;

        string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringJoin(",", values);
        sw.Stop();
        Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringBuilderAppend(",", values);
        sw.Stop();
        Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
        Console.ReadLine();
    }

    static string StringJoin(string seperator, params string[] values)
    {
        return string.Join(seperator, values);
    }

    static string StringBuilderAppend(string seperator, params string[] values)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(values[0]);
        for (int i = 1; i < values.Length; i++)
        {
            builder.Append(seperator);
            builder.Append(values[i]);
        }
        return builder.ToString();
    }
}

string.Join took 2ms on my machine and StringBuilder.Append 5ms. string.Join 在我的机器上花费了 2 毫秒,而 StringBuilder.Append 花费了 5 毫秒。 So there is noteworthy difference.所以有显着的区别。 Thanks to digAmAll for the hint.感谢 digAmAll 的提示。

如果您使用的是 .NET 4,您可以使用string.Join的重载,如果您在 List 中也有它们,则它需要一个 IEnumerable:

string.Join(", ", strings);

You could override your object's ToString() method:您可以覆盖对象的 ToString() 方法:

public override string ToString ()
{
    return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}

Yes, there can be multiple ways to do this.是的,可以有多种方法来做到这一点。

If you have List/Array of strings then you can adopt it;如果你有strings List/Array ,那么你可以采用它;

string[] myStrings = new string[] { "Hi", "stackoverflow", };
string csvString = string.Join(",", myStrings);  // csvString :: Hi,stackoverflow

If you have multiple strings then you can adopt it;如果你有多个strings ,那么你可以采用它;

string st1 = "Hi";
string st2 = "stackoverflow";
string st3 = "team";
string csvString = string.Join(",", st1, st2, st3);  // csvString :: Hi,stackoverflow,team

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM