user3395937
user3395937

Reputation: 117

Calculate the number of elements in a foreach statement

@foreach (var type in Model.GetPeople())
{
    var peopleGroup1 = persons.First();
    var category = new category { Id = person.CategoryId,;

    etc...
}

How do I count the number of 'types' in the foreach statement?

Upvotes: 0

Views: 1583

Answers (3)

Christoph Fink
Christoph Fink

Reputation: 23113

IEnumerable<T> has a Count() extension:

var people = Model.GetPeople();
var count = people.Count();

Depending on the specific type it has already a Count property:

count = people.Count;

This is available for every type implementing ICollection or ICollection<T> , but not for IQueryable<T>. An array has a Length property.

Upvotes: 7

Rachit Patel
Rachit Patel

Reputation: 862

to get count, no need to travers foreach loop. you just directly get count though

Model.GetPeople().Count

Upvotes: 3

Meysam Tolouee
Meysam Tolouee

Reputation: 579

int count = 0;
foreach (var type in Model.GetPeople())
{
    count++;
    var peopleGroup1 = persons.First();
    var category = new category { Id = person.CategoryId,;
    etc...
}

Upvotes: 2

Related Questions