考虑以下网格视图:
它目前相当空洞,但会更加人口稠密。
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();
}
我建议您对数据进行操作,而不是对网格进行操作,因此假设下面的列表是您可能绑定到网格的内容:
给定类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