C# 列表到数组问题

标签 c#

对 C# 还很陌生,所以要温柔一点:)

我有一些代码可以读取 CSV 文件并将输出存储在列表中。我使用列表而不是数组,因为 CSV 中的条目数尚未确定。从文件创建列表后,我想将其传递给希尔排序方法,因为这是程序的目的。为此,我首先要将列表转换为整数数组。我已经尝试过 .ToArray 方法,但它似乎对我不起作用。我遇到异常

Cannot Implicilty convert type String[][] to string[].

我知道我在做一些愚蠢的事情,但似乎无法找出是什么......任何帮助将不胜感激。

//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/

相关文章:

c# - 如何调用不在.NET中开发的Web服务

c# - 数组写入的性能影响比预期的要大得多

c# - 使用 Microsoft Sync Framework 2.1 同步整个数据库

c# - 如何使用 StructureMap 将服务注入(inject) XAML 引用的 ViewModel?

c# - 如何在运行时确定接口(interface)成员是否已实现?

c# - 不能修改返回值,因为它不是变量

c# - SelectedIndexChanged不触发ComboBox

c# - 用于对集合进行排序的 LINQ 查询

c# - AOP 与元编程

c# - Roslyn 编译器用零优化函数调用乘法