tags:

views:

775

answers:

4

Hello all,

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

+4  A: 

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 (=>).

RichardOD
I think I read because it is located within an if statement that it can't access anything outside of itself, not sure if that is true? As I am still getting the "The name 'a' does not exist in the current context error"
ClareBear
Can you post your now updated code?
RichardOD
I have updated my question with the updated code.
ClareBear
You're using >= instead of =>
RichardOD
+1  A: 

..or with just one exit point:

var result = from a in xxxx select a;

Func<string, bool> func = null;

if(!string.IsNullOrEmpty(personName))
{
func = (a) => {a.forename.Contains(personName) || a.surname.Contains(personName)};    
}

else if(!string.IsNullOrEmpty(dateFrom))
{
func = (a) => {a.appStartDateTime >= dateFrom.Date};
}

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

return result.Where(func);
Lee Smith
+1  A: 
Mike Two
A: 

You can also combine the predicates and make the logic shorter and easier to read:

var result = from a in xxxx select a;

if (!string.IsNullOrEmpty(personName))
    result = result.Where(a => a.forename.Contains(personName) || a.surname.Contains(personName)

if (!string.IsNullOrEmpty(dateFrom))
    result = result.Where(a >= a.appStartDateTime >= dateFrom.Date)

return result;

This method of combining predicates works well with 'AND' conditions. If you need to 'OR' conditions, it's a little bit more involved. Thankfully, Joe Albahari has created PredicateBuilder (as part of LINQKit) that helps with this greatly.

Hope this helps.

Joepro