如何将List<string>转化为string

Convert List, string. A List can be converted to a string. This is possible with the ToArray method on the List type. We can also convert a string into a List.Conversions
The StringBuilder type helps with certain conversions, which are done with loops. When using StringBuilder, we must be careful with a trailing delimiter.
First example. We use the string.Join method to combine a List of strings into one string. The output can be used as a CSV record. On new .NET Framework versions, ToArray is not required.

However:In previous versions, we had to call ToArray on a List before using Join. In older programs this is still required.

List

Based on: .NET 4

C# program that converts List

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<string> dogs = new List<string>();
	dogs.Add("Aigi"); // Add string 1
	dogs.Add("Spitz"); // 2
	dogs.Add("Mastiff"); // 3
	dogs.Add("Finnish Spitz"); // 4
	dogs.Add("Briard"); // 5

	string dogCsv = string.Join(",", dogs.ToArray());
	Console.WriteLine(dogCsv);
    }
}

Output

Aigi,Spitz,Mastiff,Finnish Spitz,Briard

Example 2. Here we use the StringBuilder class to convert a List to a single string. Note that you can convert a List of any object type into a string this way.StringBuilder

Final delimiter:The example has a final delimiter on the end. This is not present in code that uses string.Join. It can be inconvenient.

TrimEnd:Sometimes, it is good to remove the end delimiter with TrimEnd. Other times it is best left alone.

TrimEnd, TrimStart

C# program that uses List and StringBuilder

using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
	List<string> cats = new List<string>(); // Create new list of strings
	cats.Add("Devon Rex"); // Add string 1
	cats.Add("Manx"); // 2
	cats.Add("Munchkin"); // 3
	cats.Add("American Curl"); // 4
	cats.Add("German Rex"); // 5

	StringBuilder builder = new StringBuilder();
	foreach (string cat in cats) // Loop through all strings
	{
	    builder.Append(cat).Append("|"); // Append string to StringBuilder
	}
	string result = builder.ToString(); // Get string from StringBuilder
	Console.WriteLine(result);
    }
}

Output

Devon Rex|Manx|Munchkin|American Curl|German Rex|

Example 3. Here we convert a List of ints into a single string. The StringBuilder‘s Append method receives a variety of types. We can simply pass it the int.

And:Append() will handle the int on its own. It will convert it to a string and append it.

Performance:StringBuilder is fast for most programs. More speed could be acquired by using a char[] and then converting to a string.

Char Array

C# program that converts List types

using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
	List<int> safePrimes = new List<int>(); // Create list of ints
	safePrimes.Add(5); // Element 1
	safePrimes.Add(7); // Element 2
	safePrimes.Add(11); // Element 3
	safePrimes.Add(23); // Element 4

	StringBuilder builder = new StringBuilder();
	foreach (int safePrime in safePrimes)
	{
	    // Append each int to the StringBuilder overload.
	    builder.Append(safePrime).Append(" ");
	}
	string result = builder.ToString();
	Console.WriteLine(result);
    }
}

Output

5 7 11 23

Example 4. Finally, we get a List of strings from a string in CSV format. This requires the Split method. If you require per-item conversion, loop over the string array returned by Split.

C# program that converts string to List

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	string csv = "one,two,three"; // The input string
	string[] parts = csv.Split(‘,‘); // Call Split method
	List<string> list = new List<string>(parts); // Use List constructor
	foreach (string item in list)
	{
	    Console.WriteLine(item);
	}
    }
}

Output

one
two
three

A summary. We converted Lists and strings using the string.Join methods and the StringBuilder approach. The List is easily concatenated and stored in a database or file with these methods.

时间: 2024-10-05 04:58:33

如何将List<string>转化为string的相关文章

【Java】ArrayList&lt;String&gt;转化为String数组问题

Java的容器类Collections中toArray()方法,可以把诸如ArrayList<String>的动态数组.不定长转化静态数组.定长数组String[] 但是,如下的转化方式是错误的. String[] strArray = (String[]) arrayList.toArray(); 如果这样执行会导致如下的错误: Exception in thread "xx" java.lang.ClassCastException: [Ljava.lang.Objec

将fastjson元素转化为String[]

在fastjson中如果JSONObject中添加了 String[] 类型的元素 例如 JSONObject jo = new JSONObject(); String[] array = {"1", "2"}; jo.put("array", array); 将JSONObject中String[]提取出来需要 (String[])(((JSONArray)jo.get("array")).toArray(new Stri

Json格式转化为string格式

今天在学习Jsonp的时候,想通过服务端返回一段json数据,因为使用的服务端是NodeJs,那么就需要在js文件中实现返回json.(这里不懂的同学,可以先了解一下NodeJs的基础概念,在这里,我想大家推荐一个Nodejs视频  http://www.icoolxue.com/album/show/89). 首先,我们有这样一个json格式 var json={name:"xlt",age:25} 如果我们直接把上面这个”json对象“返回给客户端,那么客户端都不知道怎么接受(至于

android将String转化为MD5的方法+一些String常用的方法

public class StringUtils { public static String MD5Encode(String origin) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); resultString = byteArrayToHexString(md.digest(re

Java判断回文语句的程序(可变参数,String转化为char数组)

static void Huiwen(char... cs){     //char... cs  支持可变参数格式为 //(类型名... 变量名)--形参列表,相当于建立了一个长度可变的动态数组,系统根据用户需求来确定数组的长度 int b_ool=1; for(int i=0;i<cs.length/2;i++)    //length为这个可变数组的长度,注意此时长度为数组下表加1,通过cs.length-i-1可知 if(cs[i]!=cs[cs.length-i-1   // 判断 ]

mfc中CString转化为string的方法

LL(1)分析法实验的mfc做到最后因为CString转化为string的问题卡了一个多小时,也是惨,网上各种方法找过都不行.幸亏最后还是找到几行代码搞定了.特此mark一下. USES_CONVERSION; char* s_char = W2A(m_in); inString = s_char;

在js中 把 json对象转化为String对象的方法

方法1: 使用js的扩展方法 ** * json对象转字符串形式 */ function json2str(o) { var arr = []; var fmt = function(s) { if (typeof s == 'object' && s != null) return json2str(s); return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; } for (v

Convert integer to string(int类型转化为string类型)

译: 这是一个常见的问题,但是对于这个问题我没有找到一个很好的方法:如何将整数类型转化为字符串类型?我遇到过几种解决方案.我不会使用stringstream.sprintf()函数也遇到了问题,并且它是C语言的风格.函数itoa()以前工作地很好,但参考文档说: 这个函数在ANSI-C中没有被定义,并且它不是C++的一部分,但有些编译器支持 并且这个函数也是C语言风格. 我自己写了一个C++风格的函数,并且它工作起来没有错误(译者注:我不这么认为,详见后文). string convertInt

Money类型转化为String去除小数点后0解决方法

Money类型转化为String去除小数点后0从数据库提取Money类型后,字符串如:1212.0000 如何使其成为1212             注:去掉了小数点 如果是:1212.0100 使其成为   1212.01 难道要循环截取   有没有简单的方法 我要在Gridview中用到------解决方案--------------------double i = 1.1111; string s = i.ToString( "0.00 "); ------解决方案------