简体   繁体   English

如何使用C#查找行中每个元素的数量并将每行的平均值存储在另一个数组中?

[英]How to find the number of each elements in the row and store the mean of each row in another array using C#?

I am using the below code to read data from a text file row by row. 我正在使用以下代码逐行从文本文件读取数据。 I would like to assign each row into an array. 我想将每一行分配到一个数组中。 I must be able to find the number or rows/arrays and the number of elements on each one of them. 我必须能够找到数量或行/数组以及每个元素上的元素数量。

I would also like to do some manipulations on some or all rows and return their values. 我还想对某些或所有行进行一些操作,然后返回它们的值。

I get the number of rows, but is there a way to to loop something like: 我得到了行数,但是有一种方法可以循环:

    *for ( i=1 to number of rows)
    do
    mean[i]<-row[i]
    done
    return mean*


var data = System.IO.File.ReadAllText("Data.txt");

var arrays = new List<float[]>();

var lines = data.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

foreach (var line in lines)
{
    var lineArray = new List<float>();

    foreach (var s in line.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
    {
        lineArray.Add(Convert.ToSingle(s));
    }
    arrays.Add(lineArray.ToArray());

}

var numberOfRows = lines.Count();
var numberOfValues = arrays.Sum(s => s.Length);
var arrays = new List<float[]>();
//....your filling the arrays
var averages = arrays.Select(floats => floats.Average()).ToArray(); //float[]
var counts = arrays.Select(floats => floats.Count()).ToArray(); //int[]

Not sure I understood the question. 不确定我是否理解这个问题。 Do you mean something like 你的意思是

foreach (string line in File.ReadAllLines("fileName.txt")
{
...
}

Is it ok for you to use Linq ? 您可以使用Linq吗? You might need to add using System.Linq; 您可能需要using System.Linq;添加using System.Linq; at the top. 在顶部。

float floatTester = 0;
List<float[]> result = File.ReadLines(@"Data.txt")
        .Where(l => !string.IsNullOrWhiteSpace(l))
        .Select(l => new {Line = l, Fields = l.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) })
        .Select(x => x.Fields
                      .Where(f => Single.TryParse(f, out floatTester))
                      .Select(f => floatTester).ToArray())
        .ToList();

// now get your totals
int numberOfLinesWithData = result.Count;
int numberOfAllFloats = result.Sum(fa => fa.Length);

Explanation: 说明:

  1. File.ReadLines reads the lines of a file (not all at once but straming) File.ReadLines读取文件的行(不是一次全部读取,而是成帧)
  2. Where returns only elements for which the given predicate is true(fe the line must contain more than empty text) Where返回仅针对给定的断言为true的元素(FE行必须包含空比文字更)
  3. new { creates an anonymous type with the given properties(fe the fields separated by comma) new {创建具有给定属性的匿名类型(例如,用逗号分隔的字段)
  4. Then i try to parse each field to float 然后我尝试解析每个字段以浮动
  5. All that can be parsed will be added to an float[] with ToArray() 所有可以解析的内容都将通过ToArray()添加到float[]
  6. All together will be added to a List<float[]> with ToList() 所有一起将与ToList()一起添加到List<float[]>

Found an efficient way to do this. 找到了一种有效的方法。 Thanks for your input everybody! 谢谢大家的投入!

private void ReadFile()
    {
        var lines = File.ReadLines("Data.csv");
        var numbers = new List<List<double>>();
        var separators = new[] { ',', ' ' };
        /*System.Threading.Tasks.*/
        Parallel.ForEach(lines, line =>
        {
            var list = new List<double>();
            foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))
            {
                double i;

                if (double.TryParse(s, out i))
                {
                    list.Add(i);
                }
            }

            lock (numbers)
            {
                numbers.Add(list);
            }
        });

        var rowTotal = new double[numbers.Count];
        var rowMean = new double[numbers.Count];
        var totalInRow = new int[numbers.Count()];

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

            rowTotal[row] = values.Sum();
            rowMean[row] = rowTotal[row] / values.Length;
            totalInRow[row] += values.Length;
        }

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

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