有条件地平均 DataTable 中的一列数据
我有一个 DataTable 对象 dTable,其中所有 DataColumn 数据类型都是字符串或双精度。列中的某些数字不存在。即=空。现在我有下面的代码来查找平均值,并且当有值时它效果很好。
var sum = dTable.AsEnumerable().Average(x =>
{
if (dTable.Columns[col]!=null)
{
return x.Field<double>(dTable.Columns[col].ColumnName);
}
else
{
return ???;
};
});
我的问题是,当不满足条件以跳过该 x 时,我应该返回什么?当我在 dTable 中遇到空单元格时,它似乎不知道该怎么做。
或者,如果有一条完全不同的路,我应该走下去……拜托,无论如何……
I have a DataTable object, dTable, where all the DataColumn datatypes are either string or double. Some of the numbers in a column are not present. i.e. =null. Right now I have the below code finding the average and it works well when there are values.
var sum = dTable.AsEnumerable().Average(x =>
{
if (dTable.Columns[col]!=null)
{
return x.Field<double>(dTable.Columns[col].ColumnName);
}
else
{
return ???;
};
});
My question is what to I return when that condition is not satisfied to skip that x? When I encounter an empty cell in dTable it doesn't seem to know what to do.
Or if there is a totally different road I should be going down..please, by all means....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您想要做的是首先应用
Where
子句,以消除所需col
中缺少数据的任何行:I think what you'd like to do is to apply a
Where
clause first, to eliminate any rows that are missing data in the desiredcol
:使用 Linq 和Where() 子句,以便它只对适合您需要的列进行平均:
Use Linq and a Where() clause so it only averages columns that fit your need:
我可以给你写一个简单的for循环吗?并不是说你*应该走这条路,而只是一个选择,因为我不习惯你拥有的代码类型
Can I write you a simple for loop? Not that you *should go down this road, but just an option, as I'm not used to the kind of code you have
如果表中缺少该值,您能不能将其视为 0?如果是这样,那么在这种情况下您只需返回 0 即可。
但是,如果空值意味着它甚至不应该包含在平均值中......那么您需要自己计算平均值,类似于上面的帖子。
不确定我是否正确理解了这个问题......希望它有所帮助。
If the value is missing from the table can you not treat it as 0? If so then you can simply return 0 in that case.
But if empty value means that it shouldn't even be included in the average... then you need to calculate the average yourself, similar to the post above.
Not sure if I understand the question correctly... hope it helps.