Return IGrouping of anonymous IEnumerable to present on DataGrid

北城余情 提交于 2019-12-04 21:49:35

You need a class to represent each item of your sequence. This way your result wouldn't be a sequence of objects of an anonymous type, but it would be sequence of objects of a specific type.

public class Result 
{
    public int Id { get; set;}
    public int Sum { get; set; }
}

Then you will define a method like below:

public IEnumerable<Result> GetResults()
{
    data = new List<Event>() 
    {
        new Event() { PID = 1, Desc=2 },
        new Event() { PID = 1, Desc=3 },
        new Event() { PID = 2, Desc=4 },
        new Event() { PID = 2, Desc=5 },
        new Event() { PID = 3, Desc=6 }
    };

    var result = from d in data
                 group d.Desc by d.PID into pg
                 select new Result
                 { 
                     Id = pg.Key,  
                     Sum = pg.Sum()
                 };

    return result;
}

and then in your MainWindow method you will call this method.

public MainWindow()
{
    InitializeComponent();
    datagrid.ItemsSource = GetResults();
}

I have supposed that you have defined this method in the same class. It is quite possible that this is not a good practice. So if you define this method in another class, you have to create first an object of this class and later call the GetResults method of this object.

Furthermore, I attempted to make a slight change in the naming. It is more common to use camel case naming and not use capital letters for all the letters. That being said, you have also to make a slight change in your xaml code.

<DataGrid Name="datagrid" AutoGenerateColumns="False" IsReadOnly="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="id" Binding="{Binding Id}" Width="*"/>
        <DataGridTextColumn Header="Name" Binding="{Binding Sum}" Width="*"/>
    </DataGrid.Columns>
</DataGrid>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!