-2

我有一个包含以下数据的 csv 文件:

500000,0.005,6000

690000,0.003,5200

我需要将每一行添加为一个单独的数组。所以 50000、0.005、6000 将是 array1。我该怎么做?

目前我的代码将每一列添加到一个元素中。

例如 data[0] 显示 500000 690000

static void ReadFromFile(string filePath)
    {
        try
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    string[] data = line.Split(',');
                    Console.WriteLine(data[0] + " " + data[1]);
                }
            }
        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
4

3 回答 3

1

使用您提供的有限数据集...

const string test = @"500000,0.005,6000
690000,0.003,5200";

var result = test.Split('\n')
                 .Select(x=> x.Split(',')
                              .Select(y => Convert.ToDecimal(y))
                              .ToArray()
                        )
                 .ToArray();

foreach (var element in result)
{
    Console.WriteLine($"{element[0]}, {element[1]}, {element[2]}");
}

在此处输入图像描述


没有LINQ可以吗?是的,但是很乱……

const string test = @"500000,0.005,6000
690000,0.003,5200";

List<decimal[]> resultList = new List<decimal[]>();

string[] lines = test.Split('\n');

foreach (var line in lines)
{
    List<decimal> decimalValueList =  new List<decimal>();
    string[] splitValuesByComma = line.Split(',');

    foreach (string value in splitValuesByComma)
    {
        decimal convertedValue = Convert.ToDecimal(value);
        decimalValueList.Add(convertedValue);
    }

    decimal[] decimalValueArray = decimalValueList.ToArray();

    resultList.Add(decimalValueArray);
}

decimal[][] resultArray = resultList.ToArray();

这将给出与我在第一个示例中所做的完全相同的输出

于 2018-10-04T06:43:20.773 回答
0

如果您可以使用 a List<string[]>,则不必担心数组长度。在以下示例中,变量lines将是一个列表数组,例如:

[“500000”,“0.005”,“6000”]

[“690000”,“0.003”,“5200”]

static void ReadFromFile(string filePath)
{
    try
    {
        // Create an instance of StreamReader to read from a file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader(filePath))
        {
            List<string[]> lines = new List<string[]>();
            string line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                string[] splittedLine = line.Split(',');
                lines.Add(splittedLine);
            }
        }
    }
    catch (Exception e)
    {
        // Let the user know what went wrong.
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}
于 2018-10-04T06:44:47.017 回答
0

虽然其他有拆分方法,但我将有一个更“scolar”-“specified”的方法。您在文件中有一些 Csv 值。为存储在 Csv 中的该对象找到一个名称,为每一列命名,然后键入它们。定义这些字段的默认值。定义缺失列和格式错误的字段发生了什么。标题?

现在你知道你有什么,定义你想要什么。这一次:对象名称 -> 属性 -> 类型。

信不信由你,输入和输出的简单定义解决了您的问题。使用CsvHelper简化您的代码。

CSV 文件定义:

public class CsvItem_WithARealName
{
    public int data1;
    public decimal data2;
    public int goodVariableNames;
}

public class CsvItemMapper : ClassMap<CsvItem_WithARealName>
{
    public CsvItemMapper()
    {   //mapping based on index. cause file has no header.
        Map(m => m.data1).Index(0);
        Map(m => m.data2).Index(1);
        Map(m => m.goodVariableNames).Index(2);
    }
}

一个 Csv 阅读器方法,指向它会给你的 Csv 项目的文档。这里我们有一些配置:no header 和 InvariantCulture 进行十进制转换

private IEnumerable<CsvItem_WithARealName> GetCsvItems(string filePath)
{
    using (var fileReader = File.OpenText(filePath))
    using (var csvReader = new CsvHelper.CsvReader(fileReader))
    {
        csvReader.Configuration.CultureInfo = CultureInfo.InvariantCulture;
        csvReader.Configuration.HasHeaderRecord = false;
        csvReader.Configuration.RegisterClassMap<CsvItemMapper>();
        while (csvReader.Read())
        {
            var record = csvReader.GetRecord<CsvItem_WithARealName>();
            yield return record;
        }
    }
}

用法 :

var filename = "csvExemple.txt";
var items = GetCsvItems(filename);
于 2018-10-04T08:38:30.070 回答