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

时间:2017-12-19 16:37:27

标签: c# gridview iteration

考虑以下网格视图:

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();
    }

1 个答案:

答案 0 :(得分: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