鉴于KeyValuePair<string, DataRow>
,我想迭代通过特定列对每个条目进行分组的条目。
所以如果我们有KeyValuePair<StudentID, Student>
。
学生是一个包含几个圆柱学生信息的dataRow,我想按studentName
我希望能够写出如下内容:
foreach(KeyValuePair<string, DataRow> entry in Students.GroupBy(x => x.value["StudentName"].toString()))
答案 0 :(得分:1)
The .GroupBy()
LINQ method returns a grouping that contains the list of all the items that fit in that group.
foreach(IGrouping<string, DataRow> entry in Students.GroupBy(x => x.value["StudentName"].toString())) {
var studentName = entry.Key;
var studentsWithStudentName = entry.Select(x => x);
}
If your Students
collection has a type of ICollection<KeyValuePair<string, DataRow>>
, then the studentsWithStudentName
field here will have the type:
IEnumerable<KeyValuePair<string, DataRow>>
Of course you could group by any field you like (say student gender) and the grouping will contain a collection of students that match that group. You can even group by generated values, say:
Students.GroupBy(x => x.value["StudentHeight"] > 5)
This would give 2 groups, one where the Key
was true where all the students in it have a height greater than 5.