C# DataRow 清空检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2326341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:26:58  来源:igfitidea点击:

C# DataRow Empty-check

c#datarow

提问by Ash

I got this:

我懂了:

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

Then I add data to the row (or not). Lots of code, really don't know if there's anything inside the row. Depends on the input (i am importing from some files). I'd like to do something like:

然后我将数据添加到行(或不添加)。代码很多,真不知道行里面有没有什么东西。取决于输入(我从某些文件导入)。我想做类似的事情:

 if (drEntity`s EVERY CELL IS NOT EMPTY)
 {
   dtEntity.Rows.Add(drEntity);
 }
 else
 {
   //don't add, will create a new one (drEntity = dtEntity.NewRow();)
 }

Is there some nice way to check if the DataRow's every cell is empty? Or I should foreach, and check them one by one?

有什么好的方法可以检查 DataRow 的每个单元格是否为空?或者我应该foreach,并一一检查它们?

采纳答案by Rob

A simple method along the lines of:

一个简单的方法:

bool AreAllColumnsEmpty(DataRow dr)
{
 if (dr == null)
 {
  return true;
 }
 else
 {
  foreach(var value in dr.ItemArray)
  {
    if (value != null)
    {
      return false;
    }
  }
  return true;
 }
}

Should give you what you're after, and to make it "nice" (as there's nothing as far as I'm aware, in the Framework), you could wrap it up as an extension method, and then your resultant code would be:

应该给你你想要的东西,并使它“很好”(据我所知,在框架中没有任何东西),你可以将它包装为一个扩展方法,然后你的结果代码将是:

if (datarow.AreAllColumnsEmpty())
{
}
else
{
}

回答by Ash

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.

AFAIK,框架中没有这样做的方法。即使框架中支持这样的事情,它本质上也会做同样的事情。这将查看 DataRow 中的每个单元格以查看它是否为空。

回答by Aaron

You could use this:

你可以用这个:

if(drEntity.ItemArray.Where(c => IsNotEmpty(c)).ToArray().Length == 0)
{
    // Row is empty
}

IsNotEmpty(cell)would be your own implementation, checking whether the data is null or empty, based on what type of data is in the cell. If it's a simple string, it could end up looking something like this:

IsNotEmpty(cell)将是您自己的实现,根据单元格中的数据类型检查数据是 null 还是空。如果它是一个简单的字符串,它最终可能看起来像这样:

if(drEntity.ItemArray.Where(c => c != null && !c.Equals("")).ToArray().Length == 0)
{
    // Row is empty
}
else
{
    // Row is not empty
}

Still, it essentially checks each cell for emptiness, and lets you know whether all cells in the row are empty.

尽管如此,它本质上还是会检查每个单元格是否为空,并让您知道该行中的所有单元格是否都为空。

回答by Zyon

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.

也许更好的解决方案是添加一个额外的列,每行自动设置为 1。只要有一个不为空的元素,就将其更改为 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();)
 }

回答by Tommy Carlier

public static bool AreAllCellsEmpty(DataRow row)
{
  if (row == null) throw new ArgumentNullException("row");

  for (int i = row.Table.Columns.Count - 1; i >= 0; i--)
    if (!row.IsNull(i))
      return false;

  return true;
}

回答by Jeff

I did it like this:

我是这样做的:

var listOfRows = new List<DataRow>();
foreach (var row in resultTable.Rows.Cast<DataRow>())
{
    var isEmpty = row.ItemArray.All(x => x == null || (x!= null && string.IsNullOrWhiteSpace(x.ToString())));
    if (!isEmpty)
    {
        listOfRows.Add(row);
    }
}

回答by Thinhbk

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.

我想这种方法看起来更简单明了。

回答by Joe

DataTable.NewRowwill initialize each field to:

DataTable.NewRow将每个字段初始化为:

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

  • 每个DataColumn( DataColumn.DefaultValue)的默认值

  • 除了自增列 ( DataColumn.AutoIncrement == true),它将被初始化为下一个自增值。

  • 和表达式列 ( DataColumn.Expression.Length > 0) 也是一个特例;默认值将取决于计算表达式的列的默认值。

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 :)

我将把 LINQ 版本留作练习 :)

回答by Icarus

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

回答by Hyman Pines

I created an extension method (gosh I wish Java had these) called IsEmptyas follows:

我创建了一个扩展方法(天哪,我希望 Java 有这些)IsEmpty,如下所示:

public static bool IsEmpty(this DataRow row)
{
    return row == null || row.ItemArray.All(i => i is DBNull);
}

The other answers here are correct. I just felt mine lent brevity in its succinct use of Linq to Objects. BTW, this is really useful in conjunction with Excel parsing since users may tack on a row down the page (thousands of lines) with no regard to how that affects parsing the data.

这里的其他答案是正确的。我只是觉得我简洁地使用了 Linq to Objects。顺便说一句,这与 Excel 解析结合使用非常有用,因为用户可能会在页面下方添加一行(数千行),而不管这如何影响解析数据。

In the same class, I put any other helpers I found useful, like parsers so that if the field contains text that you know should be a number, you can parse it fluently. Minor pro tip for anyone new to the idea. (Anyone at SO, really? Nah!)

在同一个类中,我放置了我认为有用的任何其他帮助程序,例如解析器,以便如果字段包含您知道应该是数字的文本,您可以流畅地解析它。给刚接触这个想法的人的小专业提示。(SO 的任何人,真的吗?不!)

With that in mind, here is an enhanced version:

考虑到这一点,这是一个增强版本:

public static bool IsEmpty(this DataRow row)
{
    return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
}

public static bool IsNullEquivalent(this object value)
{
    return value == null
           || value is DBNull
           || string.IsNullOrWhiteSpace(value.ToString());
}

Now you have another useful helper, IsNullEquivalentwhich can be used in this context and any other, too. You could extend this to include things like "n/a"or "TBD"if you know that your data has placeholders like that.

现在你有了另一个有用的助手,IsNullEquivalent它可以在这个上下文中使用,也可以在任何其他上下文中使用。您可以将其扩展为包括诸如此类的内容,"n/a"或者"TBD"如果您知道您的数据具有此类占位符。