2010-03-07 278 views
2

我有一个我从Excel数据构建的Datable,但有时Excel会返回所有字段为空的行。如何用linq过滤掉DataTable中的空行?

我想过滤这些通常不考虑列名称。

我认为Linq会很好地做到这一点,但有一点麻烦让这种情况发生。

到目前为止,这是我得到:

var nonemptyrows = from r in table.AsEnumerable() 
               from f in r.ItemArray 
                where f != null 
                select r; 

但它不能令人信服。任何人都可以看到我错过了什么,或者如果我在错误的轨道上?

在此先感谢!

回答

4

像这样:

table.AsEnumerable() 
    .Where(r => r.ItemArray.Any(v => v != null && v != DBNull.Value)) 

或者,使用查询理解语法:

from r in table.AsEnumerable() 
where r.ItemArray.Any(v => v != null && v != DBNull.Value) 
+0

是不可能确保1列不是像列号2是非空的只是不是空。我的代码现在是'IEnumerable refIds =(从datarow在dataTable.AsEnumerable() select dataRow.Field (dataColumn.ColumnName));'。当我使用refIds.ToList()时,得到无效的转换异常。 – Saravanan 2011-10-09 09:43:21

+0

编辑:请注意,IEnumerable是String类型的,我不提取唯一的id,因为它们不能为null。 – Saravanan 2011-10-09 09:59:54

3

有点清洁,使用表列:

var nonemptyrows = from row in table.AsEnumerable() 
        where table.Columns.Any(col => !row.IsNull(col)) 
        select row; 
+0

这也会更快。 – SLaks 2010-03-07 16:54:03

+0

我通常做table.OfType ()来定义DataTable并将对象中的行转换为DataRow。但是,如果其中一行最终为空,则不确定行为。 – Will 2010-03-07 16:55:40

+0

DataTable中不能有空行。并且你不需要'OfType ()',因为DataTable的项目总是DataRows,所以你可以'Cast ()'(它是相同的,但是不过滤类型) – 2010-03-07 17:09:29

1

感谢您的答复!在我发布后,下面这个想法打我,它对我有用:

var nonemptyrows = from r in table.Rows.Cast<DataRow>() where r.ItemArray.All(c => c != DBNull.Value) select r;