在lambda表达式中分配局部变量

时间:2013-11-17 11:54:46

标签: c# lambda

我有一个lambda表达式,需要在其中分配一个局部变量,以避免每个结果集调用两次RetrieveAge(Datetime birthDate)。

我的lambda表达式如下所示:

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();

我正在努力实现以下目标:

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();

但我无法弄清楚如何正确地做到这一点。任何提示或建议都会受到赞赏。

4 个答案:

答案 0 :(得分:4)

你几乎就在那里 - 你需要添加一个return和一个分号:

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();

答案 1 :(得分:1)

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();

答案 2 :(得分: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();

答案 3 :(得分: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();