简体   繁体   English

在列中找到最大数值时,如何忽略列中非数值的数据?

[英]How can I ignore data that is not of numerical value in a column when finding the max numerical value in the column?

I have a column in a datatable that normally consist of numerical values but there are rare occasions where letters will be present in the column. 我在数据表中有一列,通常由数值组成,但在极少数情况下,列中会出现字母。 This is due to customize equipment taking measurements and when a measurement is out of range of its limits a word or abbreviation is recorded. 这是由于进行测量的定制设备导致的,并且当测量超出其限制范围时,将记录一个单词或缩写。 With that being said I am having a problem getting the max numerical value from the column because one or more rows might contain letters. 话虽如此,我在从列中获取最大数值时遇到了问题,因为一个或多个行可能包含字母。

I get the error message "Object cannot be cast from DBNull to other types "!! 我收到错误消息“无法将对象从DBNull强制转换为其他类型”!

  Decimal maxDataValue = Convert.ToDecimal(mainDataTable.Compute("max([Data])", string.Empty));
  Decimal roundMaxData = Math.Round(maxDataValue);

is it a way to work around rows who contain letters and find the max numerical value in the column? 这是一种解决包含字母的行并在列中找到最大数值的方法吗?

The error you're seeing is saying that there are also null values in your data too. 您看到的错误是说您的数据中也有空值。 The other problem of having string data in the column you are trying to sum makes it difficult to use Compute directly. 试图求和的列中包含字符串数据的另一个问题使直接使用Compute变得困难。 You could convert the DataTable to an Enumerable though and operate on it using Linq. 您可以将DataTable转换为Enumerable,然后使用Linq对其进行操作。 Something like this could work...which returns 6.25 as the result. 这样的事情可能会起作用...结果将返回6.25

var data = new DataTable();
data.Columns.Add("Data", typeof(string));
data.Rows.Add("1");
data.Rows.Add("2.0");
data.Rows.Add("3.25 kg");
data.Rows.Add(DBNull.Value);

var sum = data.AsEnumerable()
.Where(d => d["Data"] != DBNull.Value)
.Sum(d =>
{
    var columnData = d["Data"].ToString();
    var numericalString = new string(columnData.Where(c => char.IsDigit(c) || c == '.').ToArray());
    var numericalValue = decimal.Parse(numericalString);

    return numericalValue;
});

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

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