How to show the grouping data in a DataGrid? - Sum

2019-04-13 09:56发布

问题:

I've got this class:

public enum KindOfPerson
{
    Student, Teacher, ...
}

public class Person
{
    // This contains only numbers between 0 and 1
    public double ScorePercent { get; set; }
    public KindOfPerson Type { get; set; }
}

I have a people list and then I apply this LINQ function ot get another list which is classified by KindOfPerson and calculates the average score of all the people belong to that KindOfPerson:

var groupedLists = peopleList.GroupBy(person => person.Type)
                         .OrderBy(group => group.Key)
                         .Select(group => new {
                             People = group.ToList(),
                             AverageScore = group.Average(p => p.ScorePercent)
                          })
                          .ToList();

I'd like t show this list in a DataGrid but I don't have any idea to do it.

I'm trying to do this:

[DATAGRID]

Student AVERAGE SCORE: XXX

  • SCORE PERCENT 1

  • SCORE PERCENT 2

Teacher AVERAGE SCORE: YYY

  • SCORE PERCENT 1

  • SCORE PERCENT 2

Something like that, grupping by.

UPDATE

I think this code can help us: http://leeontech.wordpress.com/2010/02/01/summary-row-in-datagrid/

回答1:

Here you find an example on how grouping is done with the DataGrid. Here is another link on how implement grouping.

Principally it's done like in all groupable WPF-controls. However be aware that DataGrid loose the capability of UI virtualization if you use grouping functionality. Therefore it is generally not a good idea to create huge lists with grouped data.

For the model, I recommend that you create a view-model that is used for each line item. This VM provides all neceessary properties such as ScorePercent1, ScorePercent2 and also the grouping title.



回答2:

You either need to use a different kind of view, like a TreeView, or you'd need to have a column in your DataGrid that contains yet another DataGrid (or other data container) per row in the DataGrid.

Based on what you're trying to show, it seems like a TreeView is really what you're looking for.



回答3:

If you're able to use a third part component, I would suggest the RadGrid from Telerik. It has built in grouping/detail capabilities capabilities.

If you need something free, you might check out this link:

http://www.vbknowledgebase.com/?Id=125&Desc=Asp.Net-Hierarchical-GridView



标签: c# wpf oop