Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ WHERE clause using if statements

Tags:

c#

.net

linq

I am using c#.net

I have two textboxes which if !empty need to be part of a WHERE clause within a LINQ query.

Here is my code

var result = from a in xxxx select a;

if(!string.IsNullOrEmpty(personName))
{
    return result.Where(a >= a.forename.Contains(personName) || a.surname.Contains(personName)     
}
else if(!string.IsNullOrEmpty(dateFrom))
{
    return result.Where(a >= a.appStartDateTime >= dateFrom.Date)
}
else if(!string.IsNullOrEmpty(personName) && !string.IsNullOrEmpty(dateFrom))
{
    return result.Where(a >= a.forename.Contains(personName) || a.surname.Contains(personName) &&   a.appStartDateTime >= dateFrom.Date);
}

I thought this would work but it doesn't like the .Where and I cant access the 'a' for example a.forename (The name 'a' does not exist in the current context)

What am I going wrong, or can this not actually be done?

Thanks in advance for any help.

Clare

like image 327
ClareBear Avatar asked Sep 30 '09 10:09

ClareBear


2 Answers

Instead of this:

result.Where(a.forename.Contains(personName))

Try this:

result.Where(a => a.forename.Contains(personName))

You appear to be missing the Lambda operator (=>).

like image 154
RichardOD Avatar answered Oct 03 '22 00:10

RichardOD


try this


var result = from a in xxxx select a
    where (string.IsNullOrEmpty(personName) || a.forename.Contains(personName)
          || a.surname.Contains(personName))
          && (string.IsNullOrEmpty(dateFrom)
          || a.appStartDateTime >= DateTime.Parse(dateFrom).Date);

dateFrom appears to be a string so you have to parse it to get a date time.

This logic should work but I have not tested it. I could be wrong.

You seem to only care if the forename or surname contain personName if the personName is not null or empty. So you can rewrite it to return things if the personName is null or empty or the fore or sur name contains person name. Since the || operator is short circuiting it will not check Contains if the personName is null or empty.

like image 45
Mike Two Avatar answered Oct 03 '22 00:10

Mike Two