Home > Backend Development > C#.Net Tutorial > How to merge C# List into string according to delimiter

How to merge C# List into string according to delimiter

高洛峰
Release: 2016-12-15 15:52:39
Original
2593 people have browsed it

This article is a record of knowledge points. It mainly describes how to merge List generic collections into a string string based on delimiters (such as commas). Before the earliest times, loops were often used to concatenate strings. This method not only requires writing more code, but also consumes more system resources. Nowadays, the method string.Join(string separator, string[] value) is generally used to merge the sets into strings through separators.

Here is the description of the string.Join method:

//
// 摘要: 
//     在指定 System.String 数组的每个元素之间串联指定
//     的分隔符 System.String,从而产生单个串联的字符串。
//
// 参数: 
//   separator:
//     System.String。
//
//   value:
//     一个 System.String 数组。
//
// 返回结果: 
//     System.String,包含与 separator 字符串交错的 value 的元素。
//
// 异常: 
//   System.ArgumentNullException:
//     value 为 null。
Copy after login

The following is a specific example. The example is run in the console application. Just copy the following code to the console application and run it:

static void Main(string[] args)
        {
            //字符串集合
            List<string> list = new List<string>();
            list.Add("a");
            list.Add("b");
            list.Add("c");
            list.Add("d");
            list.Add("e");

            /*
             * 使用string.Join()方法
             */         
            //使用"," 分隔符号将List<string>泛型集合合并成字符串
            string strTemp1 = string.Join(",", list.ToArray());
            Console.WriteLine(strTemp1);
            //使用 "-" 符号分隔将List<string>泛型集合合并成字符串
            string strTemp2 = string.Join("-", list.ToArray());
            Console.WriteLine(strTemp2);



            /*
             * 使用循环方式合成字符串
             */
            string strTemp3 = string.Empty;
            foreach (string str in list)
            {
                strTemp3 += string.Format("{0},",str);
            }
            strTemp3 = strTemp3.TrimEnd(&#39;,&#39;);
            Console.WriteLine(strTemp3);

            Console.ReadKey();           
        }
Copy after login

The output result is :

C# List<string>如何根据分隔符合并成字符串

Using string.Join, you can merge List into a string through delimiters without looping.



For more C# List related articles on how to merge into strings according to separated symbols, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template