2

I have a lambda expression in which need to assign a local variable to avoid calling my RetrieveAge(Datetime birthDate) two times per resultset.

My lambda expression looks as following:

result = myList.AsEnumerable().Where(f => DateHelper.RetrieveAge(f.Birthdate) >= 20 && DateHelper.RetrieveAge(f.Birthdate) <= 40).Select(x => new Person { Name = x.Name, Id = x.Id, Alias = x.Alias }).ToList();

I am trying to achieve something like the following:

var result = myList.AsEnumerable().Where(f => { var age = DateHelper.RetrieveAge(f.Birthdate); age >= 20 && age <= 40 }).Select(x => new Person { Name = x.Name, Id = x.Id, Alias = x.Alias }).ToList();

But I can't figure out how to do that properly. Any hints or suggestions would be mostly appreciated.

1

4 Answers 4

5

You are almost there - you need to add a return and a semicolon:

var result = myList
    .AsEnumerable()
    .Where(f => {
         var age = DateHelper.RetrieveAge(f.Birthdate);
         return age >= 20 && age <= 40; // <<== Here
    }).Select(x => new Person {
         Name = x.Name, Id = x.Id, Alias = x.Alias }
    ).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

I had actually put the semicolon on one of my attempts, but I had missed the return keyword. It is a cool trick to know about assigning local variables to be used through rest of a lambda expression. :)
2
var result = (from f in myList.AsEnumerable()
             let age = DateHelper.RetrieveAge(f.Birthdate)
             where age >= 20 && age <= 40
             select new Person { Name = f.Name, Id = f.Id, Alias = f.Alias }).ToList();

Comments

0
var result = myList.AsEnumerable()
    .Select(f => new { F = f, X = DateHelper.RetrieveAge(f.Birthdate))
    .Where(f => f.F.age >= 20 && f.F.age <= 40 })
    .Select(x => new Person { Name = f.F.Name, Id = f.F.Id, Alias = f.F.Alias })
    .ToList();

Comments

0
var result = myList.AsEnumerable().Where(f => 
{ 
    var age = DateHelper.RetrieveAge(f.Birthdate); 
    return age >= 20 && age <= 40 
}).Select(x => new Person { Name = x.Name, Id = x.Id, Alias = x.Alias }).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.