基于条件的datastruct []的平均值 [英] Average over a datastruct[] based on a condition

查看:56
本文介绍了基于条件的datastruct []的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自CSV文件的数据结构



i have a datastruct that comes from a CSV file

DataStruct[]data = new DataStruct[filearray.length];
List<string> datalist = fileArray[i].Split(',').ToList<string>();
data[i].X = Convert.ToSingle(datalist[0]);
data[i].Y = Convert.ToSingle(datalist[1]);





我想取平均值,所以如果



i'd like to take an average, so if

if(data[i].X > min && data[i].X < max )
average data[i].Y





但我不知道如何访问datastruct / list。我已经尝试过Linq的一些东西,但我不明白如何指定标准(所以我不会打扰我的错误的Linq代码)



任何建议关于如何访问这个数据结构将不胜感激。



我尝试过:



正常金额



but i don't know how to access the datastruct/list. i've tried some things with Linq but i don't understand how to specify the criteria (so i won't bother posting my wrong Linq code)

any suggestions on how to access this datastructure would be appreciated.

What I have tried:

"the normal sum"

sum = sum + data[i].Y



总是给我sum = 0


always give me sum = 0

推荐答案

你没有指定数据结构,但是让我们说它看起来像这样

You didn't specify the data structure, but let's say that it looks like this
public class MyClass {
   public int X { get; set; }
   public int Y { get; set; }
}



现在填写一些数据


Now to fill some data

MyClass[] items = new MyClass[5];

items[0] = new MyClass() { X = 1, Y = 5 };
items[1] = new MyClass() { X = 9, Y = 9 };
items[2] = new MyClass() { X = 3, Y = 2 };
items[3] = new MyClass() { X = 6, Y = 0 };
items[4] = new MyClass() { X = 2, Y = 7 };



并计算平均值Y值大于2且小于9的Y值您可以使用以下LINQ语句


And to calculate the average for Y values where X is greater than 2 and less than 9 you could have the following LINQ statement

double average = items.Where(i => i.X > 2 && i.X < 9).Average(i => i.Y);



这将选择twi项目(X = 3和X = 6)并计算平均值从值2和0得到Y.


That would select twi items (X=3 and X=6) and calculate the average for Y from values 2 and 0.


这篇关于基于条件的datastruct []的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆