C# DataRow 空检查

发布于 2024-08-22 23:37:01 字数 440 浏览 8 评论 0原文

我得到了这个:

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

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

待天淡蓝洁白时 2024-08-29 23:37:01

一个简单的方法,大致如下:

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

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

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

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
{
}
心碎的声音 2024-08-29 23:37:01

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

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

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

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

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

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());
}

现在您有了另一个有用的帮助器,IsNullEquivalent,它也可以在这种情况下使用,也可以在任何其他情况下使用。如果您知道您的数据具有这样的占位符,您可以扩展它以包含诸如 "n/a""TBD" 之类的内容。

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

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.

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

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, IsNullEquivalent which 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.

情仇皆在手 2024-08-29 23:37:01

我更喜欢汤米·卡利尔的方法,但有一点改变。

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

  return true;

我认为这种方法看起来更简单、更干净。

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

您的好友蓝忘机已上羡 2024-08-29 23:37:01
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;
}
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;
}
紙鸢 2024-08-29 23:37:01

我知道这个问题已经得到解答,这是一个老问题,但这里有一个扩展方法可以执行相同的操作:

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()));            
    }
}

并且您可以像这样使用它:

if (dr.AreAllCellsEmpty())
// etc

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
电影里的梦 2024-08-29 23:37:01

您可以使用以下代码:

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

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

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

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

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:

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.

葬﹪忆之殇 2024-08-29 23:37:01

您可以使用

If(String.concat(Dr.itemArray).length>0)

Or

string.isnullorempty(String.concat(Dr.itemArray))

来检查空的或空白的数据行

You can either use

If(String.concat(Dr.itemArray).length>0)

Or

string.isnullorempty(String.concat(Dr.itemArray))

To check empty or blank datarow.

楠木可依 2024-08-29 23:37:01

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

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

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

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

因此,您可能应该检查以下内容:

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;
}

我将保留 LINQ 版本作为练习:)

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

吃素的狼 2024-08-29 23:37:01

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

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.

臻嫒无言 2024-08-29 23:37:01

我是这样做的:

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);
    }
}

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);
    }
}
青巷忧颜 2024-08-29 23:37:01

也许更好的解决方案是添加一个额外的列,该列在每行上自动设置为 1。一旦有一个元素不为 null,就将其更改为 0。

然后

If(drEntitity.rows[i].coulmn[8] = 1)
{
   dtEntity.Rows.Add(drEntity);
}
 else
 {
   //don't add, will create a new one (drEntity = dtEntity.NewRow();)
 }

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();)
 }
娇纵 2024-08-29 23:37:01

要删除空条目和空条目试试这个

  foreach (var column in drEntitity.Columns.Cast<DataColumn>().ToArray())
            {
                if (drEntitity.AsEnumerable().All(dr => dr.IsNull(column) | string.IsNullOrEmpty( dr[column].ToString())))
                    drEntitity.Columns.Remove(column);
            }

To delete null and also empty entries Try this

  foreach (var column in drEntitity.Columns.Cast<DataColumn>().ToArray())
            {
                if (drEntitity.AsEnumerable().All(dr => dr.IsNull(column) | string.IsNullOrEmpty( dr[column].ToString())))
                    drEntitity.Columns.Remove(column);
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文