题
我在你网站的一个旧问题中发现了这个问题,所以我想我可以做到,但我想我错了:-)
旧帖子是 这里
我对锯齿状数组很陌生,所以做了以下代码
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,而不是做手工循环的这个...
其他提示
首先,确保将非托管资源(例如流)包装在 using 语句中。
就我个人而言,我喜欢我的 行读取器 类,它可以轻松地从文件(或实际上的其他任何内容)中读取文本行。
接下来,我要 避免使用数组 除非你真的必须这样做。 List<T>
一般来说,合作起来会更愉快。现在,如果 string.Split 做了你想要的,你可以轻松地拥有一个 List<String[]>
. 。或者,您可以使用 LINQ 完成很多工作:
var query = from line in new LineReader("c:\\practice.txt")
let parts = line.Split(',')
select new { Gender=parts[2], Amount=int.Parse(parts[3]) };
在“普通”LINQ 中从单个数据流中获取多个聚合是很棘手的(这就是 Marc Gravell 和我开发 推送 LINQ)。但是,您可以使用普通的 foreach 语句:
int totalCounter = 0, totalSum = 0;
int maleCount = 0, maleSum = 0, femaleCount = 0, femaleSum = 0;
foreach (var row in query)
{
totalCounter++;
totalSum += row.Amount;
switch (row.Gender)
{
case "male":
maleCount++;
maleSum += Amount;
break;
case "female":
femaleCount++;
femaleSum += Amount;
break;
}
}
如果您按性别对行进行分组,您可能可以使这变得更加简单,特别是如果您知道性别始终是“男性”或“女性”。
不隶属于 StackOverflow