对 C# 还很陌生,所以要温柔一点:)
我有一些代码可以读取 CSV 文件并将输出存储在列表中。我使用列表而不是数组,因为 CSV 中的条目数尚未确定。从文件创建列表后,我想将其传递给希尔排序方法,因为这是程序的目的。为此,我首先要将列表转换为整数数组。我已经尝试过 .ToArray
方法,但它似乎对我不起作用。我遇到异常
Cannot Implicilty convert type
String[][]
tostring[]
.
我知道我在做一些愚蠢的事情,但似乎无法找出是什么......任何帮助将不胜感激。
//Import DAT file and format it.
public int[] ImportDat(string path)
{
List<string[]> loadedData = new List<string[]>();
loadedData.Clear();
try
{
using (StreamReader readCSV = new StreamReader(path))
{
string line;
string[] row;
while ((line = readCSV.ReadLine()) != null)
{
row = line.Split(',');
loadedData.Add(row);
}
}
}
catch
{
MessageBox.Show("Import Failed. Please check the file is in the same folder as the executable");
}
string[] MyArray = loadedData.ToArray();
//temp Array to return a value
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
return numbers;
}
最佳答案
您似乎确实想要 CSV 文件中的一维数字列表,但您现在正在单独处理每一行。如果是这种情况,则使用:
loadedData.AddRange(row);
而不是:
loadedData.Add(row);
并将loadedData声明为List<string>
。现在您仍然需要转换为 int,因为您的方法返回 int 列表。使用 LINQ 您可以执行以下操作:
List<int> results = loadedData.Select(s=> Convert.ToInt32(s)).ToList();
您的方法也可以用 LINQ 完全表达,如下所示:
public int[] ImportDat(string path)
{
List<int> result = File.ReadAllLines(path)
.Select(line => line.Split(','))
.SelectMany(s => s)
.Select( s=> Convert.ToInt32(s))
.ToList();
return result;
}
关于C# 列表到数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5285716/