简体   繁体   English

如何将 txt 文件转换为浮点数组(在 C# 中)?

[英]How do I Convert a txt file to an array of floats (in c#)?

I've read a file into a variable in my c# project and want to convert it into an array of floats.我已将一个文件读入我的 c# 项目中的一个变量,并希望将其转换为一个浮点数组。

Here's a sample of the txt file:这是 txt 文件的示例:

-5.673

10.543

-0.322

10.048

The file contains a number, followed by a blank line and another number.该文件包含一个数字,后跟一个空行和另一个数字。

I've used the following code to read the file into my project:我使用以下代码将文件读入我的项目:

var numbers = File.ReadAllLines(@"numbers.txt")

How would i convert numbers into a float array?我如何将numbers转换为浮点数组?

Thanks谢谢

You can use Linq and float.Parse() :您可以使用Linqfloat.Parse()

var floats = numbers.Where(s => s != String.Empty).Select(s => float.Parse(s, CultureInfo.InvariantCulture)).ToArray();

But if you have incorrect data in file you will get exception.但是,如果文件中的数据不正确,则会出现异常。 To check if value is correct float use float.TryParse() .要检查值是否正确float使用float.TryParse()

变量var的类型是String[]因此在这种情况下,您可以从数组的偶数位置获取值,然后转换为float

Your program should loop through each line in the file which are currently stored in the numbers variable, which is of type String[] , check if the value of the line is empty, and if not, convert it to a float and add it to our array of floats.您的程序应该遍历文件中当前存储在numbers变量中的每一行,它是String[]类型,检查该行的值是否为空,如果不是,将其转换为浮点数并将其添加到我们的浮动数组。

Bringing this all together would look something like this:将所有这些放在一起看起来像这样:

string[] numbers = File.ReadAllLines(@"numbers.txt");

// Create a list we can add the numbers we're parsing to. 
List<float> parsedNumbers = new List<float>() ;

for (int i = 0; i < numbers.Length; i++) 
{
    // Check if the current number is an empty line
    if (numbers[i].IsNullOrEmpty()) 
    {
        continue;
    }
    // If not, try to convert the value to a float
    if (float.TryParse(numbers[i], out float parsedValue))
    {
        // If the conversion was successful, add it to the parsed float list 
        parsedNumbers.Add(parsedValue);
    }
} 

// Convert the list to an array
float[] floatArray = new float[parsedNumbers.Length];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM