C#-删除不包含数值的数据表中的数据行

问题描述 投票:0回答:2

我希望能够删除不包含数字数据的数组中包含空值的数据表中的数据行。

[尝试修改下面的代码,该代码将转置数据表以供Google Visualization API使用:

private DataTable TransposeOpiate(DataTable inputTable)
{
    DataTable outputTable = new DataTable();

    // Add columns by looping rows

    // Header row's first column is same as in inputTable
    outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());

    // Header row's second column onwards, 'inputTable's first column taken
    foreach (DataRow inRow in inputTable.Rows)
    {
        string newColName = inRow[0].ToString();
        outputTable.Columns.Add(newColName);
    }

    // Add rows by looping columns        
    for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
    {
        DataRow newRow = outputTable.NewRow();

        // First column is inputTable's Header row's second column
        newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
        for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
        {
            string colValue = inputTable.Rows[cCount][rCount].ToString();
            newRow[cCount + 1] = colValue;
        }

        outputTable.Rows.Add(newRow);
    }

    return outputTable;
}

例如,在改进行下面显示的智能感知输出中,此后的值不包含数据(通常为数字值),而是包含空索引:

enter image description here

如果这些行采用上述格式,我必须能够删除它们,如何修改我的代码以执行此操作?

c# datatables datarow
2个回答
0
投票

您可以尝试这样的事情(注释在代码中:)>

private void CheckColumns()
{
    //table which we want to check
    DataTable table = new DataTable();
    //add column definition - first column will be string, other two are int columns
    table.Columns.Add("string column", typeof(string));
    table.Columns.Add("int column 1", typeof(int));
    table.Columns.Add("int column 2", typeof(int));

    //add data - in this example rows "abc" and "ghi" are valid because they have at least one numeric column
    table.Rows.Add(new object[] { "abc", 1, 2 });
    table.Rows.Add(new object[] { "def", null, null });
    table.Rows.Add(new object[] { "ghi", null, 2 });
    table.Rows.Add(new object[] { "jkl", null, null });

    //filter rows in a way, using Linq, that rows are filtered where at least one column has numeric value
    var validRows = table.Rows.OfType<DataRow>().Where(r => r.ItemArray.Any(c => IsNumeric(c))).ToList();
}

//this is helper method that code will call for each value in each row
private bool IsNumeric(object value)
{
    int outputValue;
    return int.TryParse(value.ToString(), out outputValue);
}

如果您使用十进制值,则应在decimal.TyrParse方法中将IsNumeric设置为ununes。

如果需要确保除第一列外的所有列都具有数字值,可以这样做(跳过每行的第一个值并检查所有其他值是否均为数字)...

var validRows = table.Rows.OfType<DataRow>().Where(r => r.ItemArray.Skip(1).All(c => IsNumeric(c))).ToList();

一旦有了那些“有效的”行,就可以将该数据写入另一个表中,或者对这些数据进行任何处理...


0
投票

如果所有行单元格都为空值,为什么不设置阻止添加行的条件?

© www.soinside.com 2019 - 2024. All rights reserved.