OT_DEV
OT_DEV

Reputation: 171

Checking if List is Null inside LINQ to SQL query?

I have a List lstStudents = GetStudents() //this method can return null. Now I am trying to run this query on my DB table student,

var result = (from c in student
             where lstStudents.Contains(c.name)
             select c);

How do I check if lstStudents is not null inside the query.

Note: I know I can check it before this query is run but I cannot do that for some other reason. And if I try (lstStudents!=null) inside query it errors out.

Cannot compare elements of type 'System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported.

Any help is appreciated.

Upvotes: 1

Views: 1277

Answers (2)

Alen.Toma
Alen.Toma

Reputation: 4870

This should work

var result =  db.users.Where(x=> list != null && list.Any(a=> 
a.Contain(x.Email)));

Upvotes: -1

Antonín Lejsek
Antonín Lejsek

Reputation: 6103

public List<string> GetStudents()
{
    return null;
}

private void button1_Click(object sender, EventArgs e)
{
    using(var ed = new DataClasses1DataContext())
    {
        List<string> lstStudents = GetStudents();

        var tst = 
            (from c in ed.Baleni
            where (lstStudents ?? new List<string>()).Contains(c.b_poznamka)
            select c)
        .ToList();
    }
}

.net 4.0.0.0, works without problem (I only used different table in my database).

Upvotes: 0

Related Questions