Reputation:
I have this function that needs to be converted to a lambda statement:
public int someFunction()
{
int pCount = 0;
foreach (Top top in Tops)
{
foreach (P p in top.TopPs)
{
pCount++;
}
}
return pCount;
}
Added more clarity:
Tops and top.TopPs extends ObservableCollection
How do i do it?
Upvotes: 1
Views: 249
Reputation: 2832
Here's an alternative method:
int pCount = (from t in Tops
from p in t.TopPs
select p).Count();
Upvotes: 1
Reputation: 10408
Here you go.
var cnt = Tops.Select<Top, int>(q => q.TopPs.Count()).Sum();
got it?
Upvotes: 0
Reputation: 4906
You can just simply use Count() for that, and it's available as an extension method.
For example:
Tops.Count();
Upvotes: -1
Reputation: 51344
Something like this:
var pCount = Tops.Sum(t=>t.TopPs.Count());
Upvotes: 1
Reputation: 269658
Do you mean a LINQ query?
int count = Tops.SelectMany(x => x.TopPs).Count();
Upvotes: 5
Reputation: 76610
Use sum LINQ operator over count of the the nested collection:
Tops.Sum(t=>t.TopPs.Count());
Upvotes: 2