考虑以下网格视图:
目前相当空洞,但人口会更多。
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();
}
答案 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