tags:

views:

99

answers:

3

Hi,

I have a Datable that I have built from excel data, but sometimes excel returns rows in which all the fields are null.

I'd like to filter these out generically without regard for column names.

I think Linq would do this nicely but having a bit of trouble getting this to happen.

So far this is what I got:

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

But it's not quite there. Anyone see what I'm missing or if I'm on the wrong track?

Thanks in advance!

+2  A: 

Like this:

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

Or, using query comprehension syntax:

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

A bit cleaner, using the table columns :

var nonemptyrows = from row in table.AsEnumerable()
                   where table.Columns.Any(col => !row.IsNull(col))
                   select row;
Thomas Levesque
This will also be faster.
SLaks
I usually do table.OfType<DataRow>() to both linquify the DataTable and cast the rows from object to DataRow. Not sure the behavior if one of the rows ends up being null, however.
Will
There can't be a null row in a DataTable. And you don't need `OfType<DataRow>()`, since items of a DataTable are always DataRows, so you can just `Cast<DataRow>()` (which is the same but doesn't filter on the type)
Thomas Levesque
A: 

Thanks for your reply! right after I posted, this idea below hit me and it worked for me:

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