有条件地平均数据表中的数据列 [英] Conditionally average a column of data in a DataTable

查看:98
本文介绍了有条件地平均数据表中的数据列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataTable对象dTable,其中所有DataColumn数据类型都是字符串或双精度型.列中的某些数字不存在.即= null.现在,我用下面的代码查找平均值,当有值时,它可以很好地工作.

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 ???;
    };

});

我的问题是当不满足该条件以跳过 x 时我将返回什么?当我在dTable中遇到一个空单元格时,它似乎不知道该怎么办.

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....

推荐答案

我认为您想做的是首先应用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 desired col:

var avg = dTable.AsEnumerable()
             .Where(x => x[col] != DBNull.Value)
             .Average(x => x.Field<double>(col));

这篇关于有条件地平均数据表中的数据列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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