user194824
user194824

Reputation: 73

Lambda Expression

Can I simplify this statement with a lambda expression?

var project = from a in accounts
              from ap in a.AccountProjects
              where ap.AccountProjectID == accountProjectId
              select ap;

Upvotes: 7

Views: 540

Answers (4)

ObjectMatrix
ObjectMatrix

Reputation: 19

accounts
    .SelectMany (
        a => AccountProjects, 
        (a, ct) => 
        new  
        {
            a = a, 
            ap = ap
        }
    )
    .Where (t => (t.ap.AccountProjectID == t.a.accountProjectId))
    .Select (t => t.ap)

Upvotes: 0

Mark
Mark

Reputation: 11740

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

Whether this is actually simpler is a matter of taste.

Upvotes: 4

Ed Swangren
Ed Swangren

Reputation: 124642

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.

Upvotes: 3

Alexander
Alexander

Reputation: 1586

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.

Upvotes: 2

Related Questions