user259286
user259286

Reputation: 1005

Linq check to see is there any NULLs in a set of DataRows?

I have a set DataRows and I want to check if any of the fields in any of those rows has a NULL value in it. I came up with this below, but I'm not sure because I'm nesting an ALL.

result.AsEnumerable().AsQueryable().All(o => o.ItemArray.All(i=>i == DBNull.Value))

Hard to tell because I can't put a "watch" in lambdas.

Upvotes: 1

Views: 1225

Answers (2)

digEmAll
digEmAll

Reputation: 57210

Actually you need to use Any (in your code you will return true if All values are null) and AsQueryable() is useless in this case.

bool nullFound = result.AsEnumerable()
                       .Any(o => o.ItemArray.Any(i=>i == DBNull.Value || i == null));

Then, If you need a list of all rows with some value null, just do the following:

var rowsWithNulls = result.AsEnumerable()
                         .Where(o => o.ItemArray.Any(i=>i == DBNull.Value || i == null))
                         .ToList();

P.S.

I also added a null check to be more safe, but if you are sure to have only DBNull.Value, you can remove it.

Upvotes: 1

Rob
Rob

Reputation: 6871

Not sure if this is the correct answer. I'm also rather new to Linq, but i believe you can do something like this;

result.AsEnumerable().AsQueryable().SingleOrDefault(o => o.ItemArray.All(i=>i == DBNull.Value))

This will return an list of items or null if there aren't any. Not sure if you can also nest it, but don't see why it wouldn't be possible

Upvotes: 0

Related Questions