user677607
user677607

Reputation:

How do I do the following using Lambda or Linq statement?

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

Answers (7)

aligray
aligray

Reputation: 2832

Here's an alternative method:

    int pCount = (from t in Tops
                  from p in t.TopPs
                  select p).Count();

Upvotes: 1

Glenn Ferrie
Glenn Ferrie

Reputation: 10408

Here you go.

var cnt = Tops.Select<Top, int>(q => q.TopPs.Count()).Sum();

got it?

Upvotes: 0

Eriawan Kusumawardhono
Eriawan Kusumawardhono

Reputation: 4906

You can just simply use Count() for that, and it's available as an extension method.

For example:

Tops.Count();

Upvotes: -1

Chris Shain
Chris Shain

Reputation: 51344

Something like this:

var pCount = Tops.Sum(t=>t.TopPs.Count());

Upvotes: 1

LukeH
LukeH

Reputation: 269658

Do you mean a LINQ query?

int count = Tops.SelectMany(x => x.TopPs).Count();

Upvotes: 5

Anthony Pegram
Anthony Pegram

Reputation: 126992

int count = Tops.Sum(top => top.TopPs.Count());

Upvotes: 8

Igor Zevaka
Igor Zevaka

Reputation: 76610

Use sum LINQ operator over count of the the nested collection:

Tops.Sum(t=>t.TopPs.Count());

Upvotes: 2

Related Questions