Joao Paulo
Joao Paulo

Reputation: 1103

How to count itens in a list using foreach and one condition?

I have an 'foreach';

 foreach (var item in Model.LstUnidadesGerenciais)
 {
     var count = Model.LstUnidadesGerenciais.Count;
 }

I need to get count with one condition like this:

 foreach (var item in Model.LstUnidadesGerenciais)
 {
     if (item.Level == 1)
     {
          var count = Model.LstUnidadesGerenciaisWITHCONDITION.Count;
     }
 }

I think this is simple, but I'm very begginer in C#

Thank you!

Upvotes: 0

Views: 206

Answers (4)

Rohit Vats
Rohit Vats

Reputation: 81313

Use Count method of LINQ -

var count = Model.LstUnidadesGerenciais.Count(i => i.Level == 1);

Upvotes: 2

L.B
L.B

Reputation: 116188

Using Linq

var cnt = Model.LstUnidadesGerenciais.Count(x=>x.Level==1);

Upvotes: 7

ChrisK
ChrisK

Reputation: 1218

In the first example, you don't need the foreach loop. You can tell, because you never use the item, you use the collection instead. I think you need to understand what foreach does here:

foreach (var item in Model.LstUnidadesGerenciais)
 {
     var count = Model.LstUnidadesGerenciais.Count;
 }

foreach will iterate over Model.LstUnidadesGerenciais. This means that for every item in Model.LstUnidadesGerenciais, the code inside the curly brackets is executed, with var item containing the current item of the collection. See MSDN for detailed information

As for the second example: You need a variable that contains a number. In the foreach loop you can increment the variable like:

int count = 0;

foreach (var item in Model.LstUnidadesGerenciais)
 {
     if (item.Level == 1)
     {
          count++;
     }
 }

Upvotes: 0

Zbigniew
Zbigniew

Reputation: 27614

You can use LINQ Where to select items matching criteria (Level == 1):

var count = Model.LstUnidadesGerenciais.Where(i => i.Level == 1).Count();

Upvotes: 3

Related Questions