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

发布于 2024-10-15 08:04:50 字数 260 浏览 6 评论 0原文

我有一个包含许多值的对象,其中一些值(并非对象中的所有值)需要放入 CSV 字符串。我的方法是这样的:

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

有没有更好、更优雅的方法?

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. My approach was this:

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

Is there is a better, more elegant way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

嘦怹 2024-10-22 08:04:50

如果将所有值放入一个数组中,至少可以使用 string.Join。

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

您还可以使用 string.Join 的重载,将 params string 作为第二个参数,如下所示:

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

If you put all your values in an array, at least you can use 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 csvString = string.Join(",", value1, value2, value3, ...);
最丧也最甜 2024-10-22 08:04:50

另一种方法是使用 System.Configuration 命名空间/程序集中的 CommaDelimitedStringCollection 类。它的行为类似于列表,而且它有一个重写的 ToString 方法,该方法返回一个以逗号分隔的字符串。

优点 - 比数组更灵活。

缺点 - 您不能传递包含逗号的字符串。

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();

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

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

Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.

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
转角预定愛 2024-10-22 08:04:50

您可以使用 string.Join< /a> 方法执行诸如 string.Join(",", o.Number, o.Id, o.whatever, ...) 之类的操作。

编辑:正如 digEmAll 所说, string.Join 比 StringBuilder 更快。他们使用 string.Join 的外部实现。

分析代码(当然在没有调试符号的版本中运行):

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 在我的机器上花费了 2 毫秒,而 StringBuilder.Append 花费了 5 毫秒。因此,存在显着差异。感谢 digAmAll 的提示。

You can use the string.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...).

edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the 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. So there is noteworthy difference. Thanks to digAmAll for the hint.

薔薇婲 2024-10-22 08:04:50

如果您使用的是 .NET 4,则可以使用 string.Join 的重载,该重载采用 IEnumerable(如果列表中也有它们):

string.Join(", ", strings);

If you're using .NET 4 you can use the overload for string.Join that takes an IEnumerable if you have them in a List, too:

string.Join(", ", strings);
心安伴我暖 2024-10-22 08:04:50

您可以重写对象的 ToString() 方法:

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

You could override your object's ToString() method:

public override string ToString ()
{
    return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}
情话难免假 2024-10-22 08:04:50

是的,可以有多种方法来做到这一点。

如果您有字符串列表/数组,那么您可以采用它;

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

如果你有多个字符串那么你可以采用它;

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

Yes, there can be multiple ways to do this.

If you have List/Array of strings then you can adopt it;

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

If you have multiple strings then you can adopt it;

string st1 = "Hi";
string st2 = "stackoverflow";
string st3 = "team";
string csvString = string.Join(",", st1, st2, st3);  // csvString :: Hi,stackoverflow,team
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文