如何迭代单个GridView列中的所有条目?

问题描述 投票:0回答:1

考虑以下网格视图:

enter image description here

它目前相当空洞,但会更加人口稠密。

peronID列将永远在同一个地方。如何迭代第一列,计算所有personID等于给定数量?像这样的东西(伪代码):

foreach element in personID
if element == 25
    count += 1

填充GridView的代码:

    private void DisplayTable()
    {
        LibraryEntities1 myDB = new LibraryEntities1();
        var people = myDB.People;
        gridViewPeople.DataSource = people.ToList();
        gridViewPeople.DataBind();
    }
c# gridview iteration
1个回答
1
投票

我建议您对数据进行操作,而不是对网格进行操作,因此假设下面的列表是您可能绑定到网格的内容:

给定类Person

class Person
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}

你可以像在SQL中那样进行分组和求和:

List<Person> persons = new List<Person>{
    new Person{ PersonID = 13,  PersonName = "Foo" },
    new Person{ PersonID = 13,  PersonName = "Foo" },
    new Person{ PersonID = 15,  PersonName = "Foo" }
};

var grp = persons.GroupBy(p => p.PersonID)
    .Select(p => new {pid = p.Key, count = p.Count()});

foreach (var element in grp)
{
    Console.WriteLine($"PersonID = {element.pid}, Count of Person = {element.count}");
}

输出:

PersonID = 13, Count of Person = 2
PersonID = 15, Count of Person = 1
© www.soinside.com 2019 - 2024. All rights reserved.