我能用Lambda表达式简化这个语句吗?
var project = from a in accounts
from ap in a.AccountProjects
where ap.AccountProjectID == accountProjectId
select ap;
var project = accounts.SelectMany(a => a.AccountProjects)
.Where(x => x.AccountProjectID == accountProjectId);
var project = accounts.Select(a => a.AccountProjects)
.Where(x => x.AccountProjectID == accountProjectId);
就可读性而言,我认为使用几个循环比lambda解决方案更好,而且我认为你的解决方案比循环更好。
List<Account> filteredAccounts = new List<Account>();
accounts.ForEach(a => { if (a.AccountProjectID == accountProjectId) filteredAccounts.Add(a); });
虽然这段代码不如你的LINQ语句易读,但我更喜欢使用这两行代码而不是accounts.Select......
而且这段代码肯定比较优化,性能也更好,我认为这点非常重要。
ToList()
相比有什么好处? - Jon Skeetaccounts
.SelectMany (
a => AccountProjects,
(a, ct) =>
new
{
a = a,
ap = ap
}
)
.Where (t => (t.ap.AccountProjectID == t.a.accountProjectId))
.Select (t => t.ap)