gpt4 book ai didi

c# - 从文本文件读取到锯齿状数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:28:13 25 4
gpt4 key购买 nike

我在你网站的一个旧问题中发现了这个问题,所以我认为我可以做到,但我想我错了:-)

旧帖子是here

我是锯齿状数组的新手,下面的代码也是如此

StreamReader rows = new StreamReader("c:\\practice.txt");
string line;
int i;
i=1;
while ((line = rows.ReadLine()) != null)
{
String[][]rows = new String [i][]; ;
rows = rows.ReadLine();
String[][] rows = new string[S.Length][];
i++;
}
for (int i; i < S.Length; i++)
{

row[i] = S[I].Split(',');

}

int totalCounter = 0, totalSum = 0;
// etc
foreach(string[] row in rows)
{
int m1 = int.Parse(row[3]);
totalCounter++;
totalSum += m1;
switch(row[2])
{
case "male":
maleCount++;
maleSum += m1;
break;
case "female":
femaleCount++;
femaleSum += m1;
break;
}
}

我知道我犯了重大错误但至少我试过任何人都可以帮助我使它成为一个工作代码

最佳答案

您似乎在重复阅读这些行,或者您可能混淆了行和单元格 - 尤其是这一点看起来真的很奇怪:

        while ((line = rows.ReadLine()) != null)
{
String[][]rows = new String [i][]; ;
rows = rows.ReadLine();
String[][] rows = new string[S.Length][];
i++;
}

即重新声明行,每个循环两次调用 ReadLine 等。我怀疑你是说 string.Split?无论哪种方式,要么使用 File.ReadAllLines,要么查看昨天提供的一些选项。如果你急于使用数组,核心可能类似于:

using System;
using System.IO;
static class Program
{
static void Main()
{
string[] lines = File.ReadAllLines("foo.txt");
string[][] grid = new string[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
grid[i] = lines[i].Split(',');
}

int totalCount = 0, maleCount = 0, femaleCount = 0,
m1Total = 0, m2Total = 0, m3Total = 0,
m1MaleTotal = 0, m1FemaleTotal = 0;
foreach (string[] line in grid)
{
totalCount++;
int m1 = int.Parse(line[3]),
m2 = int.Parse(line[4]),
m3 = int.Parse(line[5]);
m1Total += m1;
m2Total += m2;
m3Total += m3;
switch (line[1].Trim())
{
case "male":
maleCount++;
m1MaleTotal += m1;
break;
case "female":
femaleCount++;
m1FemaleTotal += m1;
break;
}
}
Console.WriteLine("Rows: " + totalCount);
Console.WriteLine("Total m1: " + m1Total);
Console.WriteLine("Average m1: " + ((double)m1Total)/totalCount);
Console.WriteLine("Male Average m1: " + ((double)m1MaleTotal) / maleCount);
Console.WriteLine("Female Average m1: " + ((double)m1FemaleTotal) / femaleCount);
}
}

再一次 - 我怎么强调你应该用 LINQ 而不是手动循环来做这件事...

关于c# - 从文本文件读取到锯齿状数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/362224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com