Lambda expression

Can this statement be simplified with a lambda expression?

var project = from a in accounts from ap in a.AccountProjects where ap.AccountProjectID == accountProjectId select ap; 
+7
c # lambda
source share
4 answers

Honestly, it looks pretty clear to me. I think lambda in this case may be less readable, i.e. Something like Brandon posted below.

(abducted from Brandon's post)

 var project = accounts.Select(a => a.AccountProjects) .Where(x => x.AccountProjectID == accountProjectId); 

Regarding readability, I think a couple of loops are preferable to a lambda solution, and I think your solution is preferable to loops.

+3
source share
 var project = accounts.SelectMany(a => a.AccountProjects) .Where(x => x.AccountProjectID == accountProjectId); 

Whether it is really easier is a matter of taste.

+4
source share

I agree with Ed Swangren. It looks concise and readable.

Actually the answer to your question depends on 3 things:

  • What do you want to achieve - better readability? better performance? and etc.
  • Account Type
  • How will the resulting collection be used.

If you need better performance, and if the โ€œaccountsโ€ are a list and the resulting collection is iterated or passed to another method to iterate soon enough after these lines of code, I would do something like this:

 List<Account> filteredAccounts = new List<Account>(); accounts.ForEach(a => { if (a.AccountProjectID == accountProjectId) filteredAccounts.Add(a); }); 

Of course, this is less readable than your LINQ statement, but I would use these 2 lines, not the accounts. Choose .......

And of course, it is much better optimized for performance, and this is always important.

+2
source share
 accounts .SelectMany ( a => AccountProjects, (a, ct) => new { a = a, ap = ap } ) .Where (t => (t.ap.AccountProjectID == taaccountProjectId)) .Select (t => t.ap) 
0
source share

All Articles