计算foreach语句中的元素数

时间:2014-05-26 11:29:22

标签: c# foreach count sum

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

    etc...
}

如何计算'类型的数量'在foreach声明中?

3 个答案:

答案 0 :(得分:7)

IEnumerable<T>的扩展名为Count()

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

具体类型取决于具有Count属性的特定类型:

count = people.Count;

这适用于实施ICollectionICollection<T>的所有类型,但不适用于IQueryable<T>。数组具有Length属性。

答案 1 :(得分:3)

得到计数,不需要遍历foreach循环。你只是直接计算

Model.GetPeople().Count

答案 2 :(得分:2)

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