简体   繁体   English

在 C# 中将字符串与分隔符合并在一起

[英]Merging strings together with separator berween them in C#

I needed to merge strings that are inside List<string> together into oneliner.我需要将List<string>中的字符串合并到 oneliner 中。 I came up with simple solution but I am not sure if it's the best way to go.我想出了简单的解决方案,但我不确定这是否是 go 的最佳方法。

First version with problematic , on string start:第一个版本有问题,在字符串开始:

string benchmarkiUjemneDatyRazem = "";
foreach (string s in benchmarkiUjemne) {
    benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
}

Second version (Linq power) but still with `:第二个版本(Linq power),但仍然带有`:

string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s);

Working version without , but amount of lines makes some pain in later reading it:没有 的工作版本,但是行数使以后阅读它时有些痛苦:

   int b = 0;
   string benchmarkiUjemneDatyRazem = "";
   foreach (string s in benchmarkiUjemne) {
       if (b == 0) {
          b = 1;
          benchmarkiUjemneDatyRazem = s;
          continue;
       }
       benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
  }

Final version that I came up with was based on Linq with Subsitute to first char:我想出的最终版本是基于 Linq 并替换为第一个字符:

    string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s).Substring(1);

Is this good approach to this problem?这是解决这个问题的好方法吗? Or there's better way to actually do it?还是有更好的方法来实际做到这一点? Like using StringBuilder or so?喜欢使用 StringBuilder 左右?

If you're using.Net 4, you can use string.Join (in earlier versions this will work only if benchmarkiUjemne is a string[] ):如果您使用.Net 4,则可以使用string.Join (在早期版本中,这仅在benchmarkiUjemnestring[]时才有效):

string result = string.Join(",", benchmarkiUjemne);

If this is.Net 3.5 or older, you can still use it by calling ToArray on the list:如果这是 .Net 3.5 或更早版本,您仍然可以通过调用列表中的ToArray来使用它:

string result = string.Join(",", benchmarkiUjemne.ToArray());

Use string.Join :使用string.Join

var res = string.Join(",", benchmarkiUjemne);

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

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