0
@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?

2
  • 4
    Model.GetPeople().Count?
    – Bharadwaj
    May 26, 2014 at 11:30
  • 2
    It's really not clear what difficulties you had, the straightforward approach (without LINQ) would be a simple counter variable which you increase in the foreach. May 26, 2014 at 11:32

3 Answers 3

7

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.

5
  • If that solves the question my first question to OP is why he doesn't use a variable to count it in the foreach. You are enumerating the people twice, once in the foreach and again in Count (if it's not a list or array). May 26, 2014 at 11:34
  • Good question. One possible answer: He needs the count before the loop is complete... May 26, 2014 at 11:35
  • Or may be unaware of Count.
    – Bharadwaj
    May 26, 2014 at 11:38
  • Anyhow: If the OP tells us more about his exact problem we may can help better. At the moment there is "some guessing" involved... May 26, 2014 at 11:40
  • 1
    @TimSchmelter: Thanks for the improvement. May 26, 2014 at 11:42
3

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.