B. *_*non 119 .net c# list arraylist
我有这个代码:
String[] lineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
lineElements = line.Split(',');
. . .
Run Code Online (Sandbox Code Playgroud)
但后来认为我应该选择List而不是.但是这段代码:
List<String> listStrLineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
listStrLineElements = line.Split(',');
. . .
Run Code Online (Sandbox Code Playgroud)
...给我," 不能隐式地将类型'string []'转换为'System.Collections.Generic.List' "
Bro*_*ass 278
string.Split()
返回一个数组 - 您可以使用ToList()
以下命令将其转换为列表:
listStrLineElements = line.Split(',').ToList();
Run Code Online (Sandbox Code Playgroud)
您需要导入System.Linq才能访问.ToList()函数.
Jon*_*eet 60
使用:
List<string> list = new List<string>(array);
Run Code Online (Sandbox Code Playgroud)
或者来自LINQ:
List<string> list = array.ToList();
Run Code Online (Sandbox Code Playgroud)
或者将代码更改为不依赖于特定的实现:
IList<string> list = array; // string[] implements IList<string>
Run Code Online (Sandbox Code Playgroud)
Gau*_*avs 10
包括使用命名空间 System.Linq
List<string> stringList = line.Split(',').ToList();
Run Code Online (Sandbox Code Playgroud)
您可以轻松地使用它来迭代每个项目.
foreach(string str in stringList)
{
}
Run Code Online (Sandbox Code Playgroud)
String.Split()
返回一个数组,因此使用它将其转换为列表 ToList()
小智 7
试试这一行:
List<string> stringList = line.Split(',').ToList();
Run Code Online (Sandbox Code Playgroud)
这将读取一个 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;
}
Run Code Online (Sandbox Code Playgroud)
只是你可以使用 using System.Linq;
List<string> stringList = line.Split(',') // this is array
.ToList(); // this is a list which you can loop in all split string
Run Code Online (Sandbox Code Playgroud)