-3

I have the following (easy) table:

Table: MyDataTable

**Color**
Blue
null
Red
Yellow
null
null
Green

This query (for example):

query =
       from user in MyDataTable.AsEnumerable()
       where (user.Field<string>("Color") != null ? user.Field<string>("Color").Contains("") : false)
       select user;

shows all fields that aren't null.

Edit: Sorry my question is in the title. I would like to make a query to display only null fields. How? Regards!

karmany  
  • 39
  • 1
  • 6
  • 1
    Why do you need to write a query to return everything in your dataset? It sounds like you're wasting CPU cycles to do nothing. – evanmcdonnal Jun 20 '13 at 20:02
  • Because it's a simple query, it's an easy example. My app has a more complex query. My app only shows (by default) 10 items. Null fields generate an exception in the query and null fields aren't show in the DataGridView. – karmany   Jun 20 '13 at 20:13
  • null will not generate an exception in a query. It probably will when you try to display it in DataGridView. In which case you need something like `value ?? "null"` which basically says `if (value == null) value = "null"` where you're adding items. The point was there is no query to write here, you just call `AsEnumerable()` or `AsEnumerable().ToList()` or `.ToArray()` to convert your dt. – evanmcdonnal Jun 20 '13 at 20:19
  • Very thanks for your help. This query generates an exception: where (user.Field("Color").Contains("lu")) NullException – karmany   Jun 20 '13 at 20:22
  • Yes you're getting a NullReferenceException because you're trying to call `Contains` on a null value. It has nothing to do with your query. The code happens to be in your query but it's not specific to it, you can't call methods or access properties on null anywhere in C#. Add a check before making that call. – evanmcdonnal Jun 20 '13 at 20:28
  • Very thanks. Yes, this is my problem. A null field isn't show in my query, in my DataGridView. The problem is only with Contains(""). An empty field is show. – karmany   Jun 20 '13 at 20:37

2 Answers2

2

Remove the where clause:

var query = from user in MyDataTable.AsEnumerable()
            select user;

Or simply:

var query = MyDataTable.AsEnumerable();
Darren
  • 68,902
  • 24
  • 138
  • 144
1

I would like to make a query to display all fields (including null fields).

To display everything, just use the table directly:

query = MyDataTable.AsEnumerable();

Note that you can use String.IsNullOrEmpty to simplify your existing query:

query =
   from user in MyDataTable.AsEnumerable()
   where !string.IsNullOrEmpty(user.Field<string>("Color"))
   select user;
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373