Evgeniy Bojenov
Evgeniy Bojenov

Reputation: 21

how to check the value for null in linq?

I have a table called specifications and a list field whichs values need to be checked for null. Here is the list:

List<string> fieldList = new List<string>() { name1, name2, name3 }; //name of the fields

I already tried the following:

var checkForNull = TableInfo.Get("specifications").Fields.Where(i => fieldList.Find(x=>x==null)))

But it does not select null values.

How do I check the value and at the same time how do I save this field name to a new list?

Example: There are 3 names in my list (name1, name2, name3) and in the database are the values (name1 = 30, name2 = null, name3 = null)

So, name2 and name3 would be added to the list.

So I tried also:

TableInfo.Get("specifications").Fields.Where(i => fieldList .Contains(i.Name) && i.IsEmptyValue(i));

But this does not work.

Upvotes: 0

Views: 251

Answers (2)

Marco Salerno
Marco Salerno

Reputation: 5203

This way:

class Program
{
    static void Main(string[] args)
    {
        DataTable result = new DataTable();
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand("SELECT name, value FROM specifications", connection))
            {
                using (SqlDataAdapter reader = new SqlDataAdapter(command))
                {
                    reader.Fill(result);
                }
            }
        }

        List<string> foundNullSpecifications = result.Rows.OfType<DataRow>().Select(x => new Specification
        {
            Name = (string)x["name"],
            Value = x["value"]
        }).Where(x => x.Value == null).Select(x => x.Name).ToList();
    }
}

public class Specification
{
    public string Name { get; set; }
    public object Value { get; set; }
}

Upvotes: 1

Indrit Kello
Indrit Kello

Reputation: 1313

Use IsNullOrEmpty() method if you want to check for null or empty:

string name1, name2, name3;
name1 = "test";
name2 = null;
name3 = null;
List<string> fieldList = new List<string>() { name1, name2, name3 }; //name of the fields
var nullOrEmptyElementes = fieldList.Where(e => string.IsNullOrEmpty(e)).ToList();

Otherwise, you can just check for null values:

var nullOrEmptyElementes = fieldList.Where(e => e==null).ToList();

Using ToList() method, you can "convert" an IEnumerable<T> to a List<T>.

Upvotes: 2

Related Questions