使用C#循环未知行数

时间:2012-07-23 10:07:25

标签: c# .net arrays text-parsing

我需要为所有行循环此循环,而不仅仅是由2索引的行。另外,我在双解析中遇到错误。

是否有一种有效的方法来执行以下操作?

该文件可以有不同长度的行。因此,我需要维护一个数组来存储每一行​​的大小。

 public static void ReadFile()
    {
        int lineNo;
        List<List<double>> numbers = new List<List<double>>();
        foreach (string line in File.ReadAllLines("Data.txt"))
        {
            var list = new List<float>();
            foreach (string s in line.Split(new[]{',', ' '}, StringSplitOptions.RemoveEmptyEntries))
            {
                int i;
                if(double.TryParse(s, out i))
                {
                    list.Add(i);
                    lineNo++;
                }
            }
            numbers.Add(list);
        }

        var specialNumber = numbers[3][4];        // gives line 3 number 4
        var specialLine = numbers[2].ToArray();   //  gives an array of numbers of line 2

        double[] rowTotal;
        double[] squareRowTotal;
        double[] rowMean;

        //I need to loop this loop for all rows and not just the row indexed by 2. Also I am getting an error in the double parsing.

        for (int j=0; j<(specialLine.Length); j++)
        {
            rowTotal[2] = rowTotal[2] + numbers[2][j];
            squareRowTotal[2] = squareRowTotal[2] + numbers[2][j] * numbers[2][j];
        }

        for (int k = 0; k < lineNo; k++)
        {
            rowMean[k] = rowTotal[k] / numbers[k].Length;
        }
    }

3 个答案:

答案 0 :(得分:1)

BTW最好分割数据访问逻辑和数据处理逻辑。还要考虑声明一些类型,它将具有名称,描述双值的性质。 E.g。

public class BowlingGame
{
   private List<double> _scores = new List<double>();

   public BowlingGame(IEnumerable<double> scores)
   {
       _scores.AddRange(scores);
   }

   public double Total
   {
       get { return _scores.Sum(); }
   }

   // implementation for SquareTotal and Mean
}

从解析方法返回此实体的列表:

public static IEnumerable<BowlingGame> ParseFile()
{
   List<BowlingGame> games = new List<BowlingGame>();
   foreach (string line in File.ReadAllLines(@"c:\temp\test.csv"))
        games.Add(ParseGame(line));
   return games;
}

private static BowlingGame ParseGame(string line)
{
    var scores = new List<double>();
    foreach (string s in line.Split(new[] { ',', ' ' }))
    {
        double score;
        if (Double.TryParse(s, out score))            
             scores.Add(score);
    }

    return new BowlingGame(scores);
}

用法:

foreach(var game in GameParser.ParseFile())
{
    Console.WriteLine(game.Total);
    Console.WriteLine(game.Mean);
}

您的代码有什么问题?您已宣布

List<List<double>> numbers = new List<List<double>>();

但是尝试添加integeres列表

 var list = new List<int>();

同样double.TryParse(s, out i)需要double out参数,但是你传递的是整数。

您可以使用Linq在循环中计算您的值(在使用之前不要忘记初始化数组):

double[] rowTotal = new double[numbers.Count];

for (int rowIndex = 0; rowIndex < numbers.Count; rowIndex++)            
    rowTotal[rowIndex] = numbers[rowIndex].Sum();

}

答案 1 :(得分:0)

    public static void ReadFile()
    {
        List<List<double>> numbers = new List<List<double>>();
        foreach (string line in File.ReadAllLines(@"c:\temp\test.csv"))
        {
            var list = new List<double>();
            foreach (string s in line.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
            {
                double i;
                if (Double.TryParse(s, out i))
                {
                    list.Add(i);
                }
            }
            numbers.Add(list);
        }

        double[] rowTotal = new double[numbers.Count];
        double[] squareRowTotal = new double[numbers.Count];
        double[] rowMean = new double[numbers.Count];

        for(int row = 0; row < numbers.Count; row++)
        {
            var values = numbers[row].ToArray();

            rowTotal[row] = values.Sum();
            squareRowTotal[row] = values.Select(v => v * v).Sum();
            rowMean[row] = rowTotal[row] / rowTotal.Count();
        }
    }

答案 2 :(得分:0)

我认为你的答案应该是这样的(我使用了一些LINQ而不是循环!):

public void ReadFile()
{
    int lineNo = 0;
    List<List<double>> numbers = new List<List<double>>();
    foreach (string line in File.ReadAllLines("Data.txt"))
    {
        var list = new List<double>();
        foreach (string s in line.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
        {
            double i;
            if (double.TryParse(s, out i))
            {
                list.Add(i);
                lineNo++;
            }
        }
        numbers.Add(list);
    }

    var rowsTotal = new List<double>(numbers.Count);
    var squareRowTotal = new List<double>(numbers.Count);
    var rowMean = new List<double>(numbers.Count);

    rowsTotal.AddRange(numbers.Select(row => row.Sum()));
    squareRowTotal.AddRange(numbers.Select(row => row.Sum(d => d*d)));


    for (int k = 0; k < lineNo; k++)
    {
        rowMean[k] = rowsTotal[k] / numbers[k].Count;
    }
}