C# 如何将分隔的字符串 split() 为 List<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9263695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split() a delimited string to a List<String>
提问by B. Clay Shannon
I had this code:
我有这个代码:
String[] lineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
lineElements = line.Split(',');
. . .
but then thought I should maybe go with a List instead. But this code:
但后来想我也许应该用 List 代替。但是这段代码:
List<String> listStrLineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
listStrLineElements = line.Split(',');
. . .
...gives me, "Cannot implicitly convert type 'string[]' to 'System.Collections.Generic.List'"
...给我,“无法将类型 'string[]' 隐式转换为 'System.Collections.Generic.List'”
采纳答案by BrokenGlass
string.Split()returns an array - you can convert it to a list using ToList():
string.Split()返回一个数组 - 您可以使用ToList()以下方法将其转换为列表:
listStrLineElements = line.Split(',').ToList();
Note that you need to import System.Linqto access the .ToList()function.
请注意,您需要导入System.Linq才能访问该.ToList()功能。
回答by Jon Skeet
Either use:
要么使用:
List<string> list = new List<string>(array);
or from LINQ:
或来自 LINQ:
List<string> list = array.ToList();
Or change your code to not rely on the specific implementation:
或者更改您的代码以不依赖特定实现:
IList<string> list = array; // string[] implements IList<string>
回答by Anuja Wadatkar
string[] thisArray = myString.Split('/');//<string1/string2/string3/--->
List<string> myList = new List<string>(); //make a new string list
myList.AddRange(thisArray);
Use AddRangeto pass string[]and get a string list.
使用AddRange通过string[],并得到一个字符串列表。
回答by Gaurravs
Include using namespace System.Linq
包含 using 命名空间 System.Linq
List<string> stringList = line.Split(',').ToList();
you can make use of it with ease for iterating through each item.
您可以轻松地使用它来遍历每个项目。
foreach(string str in stringList)
{
}
String.Split()returns an array, hence convert it to a list using ToList()
String.Split()返回一个数组,因此使用 ToList()
回答by Brian Rice
This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.
这将读取一个 csv 文件,它包含一个处理双引号的 csv 行拆分器,即使 excel 打开它也可以读取。
public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
{
var result = new List<Dictionary<string, string>>();
var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.StreamReader file = new System.IO.StreamReader(fs);
string line;
int n = 0;
List<string> columns = null;
while ((line = file.ReadLine()) != null)
{
var values = SplitCsv(line);
if (n == 0)
{
columns = values;
}
else
{
var dict = new Dictionary<string, string>();
for (int i = 0; i < columns.Count; i++)
if (i < values.Count)
dict.Add(columns[i], values[i]);
result.Add(dict);
}
n++;
}
file.Close();
return result;
}
private List<string> SplitCsv(string csv)
{
var values = new List<string>();
int last = -1;
bool inQuotes = false;
int n = 0;
while (n < csv.Length)
{
switch (csv[n])
{
case '"':
inQuotes = !inQuotes;
break;
case ',':
if (!inQuotes)
{
values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
last = n;
}
break;
}
n++;
}
if (last != csv.Length - 1)
values.Add(csv.Substring(last + 1).Trim());
return values;
}
回答by Snr
Just u can use with using System.Linq;
只是你可以使用 using System.Linq;
List<string> stringList = line.Split(',') // this is array
.ToList(); // this is a list which you can loop in all split string
回答by rosecode
Try this line:
试试这一行:
List<string> stringList = line.Split(',').ToList();

