0

我正在尝试使用此策略对数据表中第五列之后的每一列中的值进行平均

List<double> mylist = new List<double>();
        for (int col = 5; col < GridData.Columns.Count; col++)
        {
            double avg = GridData.AsEnumerable()
                .Where(x => x[GridData.Columns[col]] != DBNull.Value)
             .Average(x => x.Field<double>(GridData.Columns[col]));
            mylist.Add(avg);
        }

已根据我在此 stackoverflow 问题中找到的内容进行了修改。

每次我运行它时,它都会给我一个“指定的演员表无效”错误 -.Average(x => x.Field<double>(GridData.Columns[col]));

4

2 回答 2

2

最简单的解决方案只是解析 DataTable 字段中的字符串,但您必须确保可以解析该值。检查这个:

List<double> mylist = new List<double>();
for (int col = 5; col < GridData.Columns.Count; col++)
{
       double avg = GridData.AsEnumerable()
            .Where(x => x[col] != DBNull.Value)
            .Average(x => double.Parse(x[col].ToString()));
                mylist.Add(avg);
}

甚至更好地使用TryParse

List<double> mylist = new List<double>();
for (int col = 0; col < GridData.Columns.Count; col++)
{
       double a;
       double avg = GridData.AsEnumerable()
             .Where(x => x[col] != DBNull.Value)
             .Average(x => double.TryParse(x[col].ToString(), out a) ? a:0.0);
                   mylist.Add(avg);
}

第三个,最安全但有冗余解析:

for (int col = 0; col < GridData.Columns.Count; col++)
            {
                double a;
                double avg = GridData.AsEnumerable()
                    .Where(x => x[col] != DBNull.Value && double.TryParse(x[col].ToString(), out a))
                    .Average(x => double.Parse(x[col].ToString()));
                mylist.Add(avg);
            }
于 2013-03-31T21:38:12.000 回答
1

根据您的评论,错误:

System.Data.Datarow does not contain a defintion for Field

建议通用扩展方法Field

public static T Field<T>(this DataRow row, DataColumn column)

没有找到。您是否引用了带有扩展方法的程序集DataRow

System.Data.DataSetExtensions.dll

你可能应该using为它添加一个:

using System.Data.DataSetExtensions;
于 2013-03-31T21:09:53.497 回答