C# DataRow Empty-check

后端 未结 11 1089
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 05:13

I got this:

 DataTable dtEntity = CreateDataTable();
 drEntity = dtEntity.NewRow();

Then I add data to the row (or not). Lots of code, real

相关标签:
11条回答
  • 2020-12-15 06:00

    AFAIK, there is no method that does this in the framework. Even if there was support for something like this in the framework, it would essentially be doing the same thing. And that would be looking at each cell in the DataRow to see if it is empty.

    0 讨论(0)
  • 2020-12-15 06:03

    I prefer approach of Tommy Carlier, but with a little change.

    foreach (DataColumn column in row.Table.Columns)
        if (!row.IsNull(column))
          return false;
    
      return true;
    

    I suppose this approach looks more simple and bright.

    0 讨论(0)
  • 2020-12-15 06:08

    I know this has been answered already and it's an old question, but here's an extension method to do the same:

    public static class DataExtensions
    {
        public static bool AreAllCellsEmpty(this DataRow row)
        {
            var itemArray = row.ItemArray;
            if(itemArray==null)
                return true;
            return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));            
        }
    }
    

    And you use it like so:

    if (dr.AreAllCellsEmpty())
    // etc
    
    0 讨论(0)
  • 2020-12-15 06:09

    Maybe a better solution would be to add an extra column that is automatically set to 1 on each row. As soon as there is an element that is not null change it to a 0.

    then

    If(drEntitity.rows[i].coulmn[8] = 1)
    {
       dtEntity.Rows.Add(drEntity);
    }
     else
     {
       //don't add, will create a new one (drEntity = dtEntity.NewRow();)
     }
    
    0 讨论(0)
  • 2020-12-15 06:14

    DataTable.NewRow will initialize each field to:

    • the default value for each DataColumn (DataColumn.DefaultValue)

    • except for auto-increment columns (DataColumn.AutoIncrement == true), which will be initialized to the next auto-increment value.

    • and expression columns (DataColumn.Expression.Length > 0) are also a special case; the default value will depend on the default values of columns on which the expression is calculated.

    So you should probably be checking something like:

    bool isDirty = false;
    for (int i=0; i<table.Columns.Count; i++)
    {
        if (table.Columns[i].Expression.Length > 0) continue;
        if (table.Columns[i].AutoIncrement) continue;
        if (row[i] != table.Columns[i].DefaultValue) isDirty = true;
    }
    

    I'll leave the LINQ version as an exercise :)

    0 讨论(0)
提交回复
热议问题