当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Lambda Expression

问题描述:

Can I simplify this statement with a lamda expression?

var project = from a in accounts

from ap in a.AccountProjects

where ap.AccountProjectID == accountProjectId

select ap;

网友答案:

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

(Stolen from Brandon's post)

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

As far as readability is concerned, I think that a couple of loops is preferable to the lambda solution, and I think that your solution is preferable to the loops.

网友答案:
var project = accounts.SelectMany(a => a.AccountProjects)
                      .Where(x => x.AccountProjectID == accountProjectId);

Whether this is actually simpler is a matter of taste.

网友答案:

I agree with Ed Swangren. This looks concise and readable enough.

Actually the answer to your question depends on 3 things:

  1. What you want to achieve - better readability? better performance? etc.
  2. The type of 'accounts'
  3. How the resulting collection is going to be used.

If you want better performance, and in case 'accounts' is a List, and the resulting collection will be iterated or passed to another method for iterating soon enough after these lines of code, I would do something like that:

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

Surely it's less readable then your LINQ statement, but I would use these 2 lines rather than accounts.Select.......

And surely it's much better optimized for performance, which is always important I believe.

网友答案:
accounts
    .SelectMany (
        a => AccountProjects, 
        (a, ct) => 
        new  
        {
            a = a, 
            ap = ap
        }
    )
    .Where (t => (t.ap.AccountProjectID == t.a.accountProjectId))
    .Select (t => t.ap)
分享给朋友:
您可能感兴趣的文章:
随机阅读: