简体   繁体   English

如何分组然后转动数据

[英]How to group and then pivot data

I'm trying to group and then pivot some data to display on asp.net view. 我正在尝试分组然后转动一些数据以显示在asp.net视图上。

Here is my View Model class. 这是我的View Model类。

public class myModel
{

    public string id { get; set; }
    public string fund{ get; set; }
    public string account{ get; set; }
    public string amount{ get; set; }

} }

Here is a sample data returned from database 这是从数据库返回的示例数据

id   fund       account   amt
1     101       1001      25.70
2     101       1001      10.00
3     101       1001      12.00
4     101       1002      -5.0
5     201       2001      12.00
6     201       2001      11.00

Now I have a query that returns above data and maps it to the model mentioned above. 现在我有一个查询返回上面的数据并将其映射到上面提到的模型。 Essentially I have a list of objects with above mentioned data. 基本上我有一个带有上述数据的对象列表。

Now I want to group and sum this data and display like below in my view. 现在我想对这些数据进行分组和求和,并在我的视图中显示如下。

fund
    account      sum of all amt
    account       sum of all amt
fund
    account       sum of all amt
    account       sum of all amt

so something like 所以像


101
   1001      47.00
   1002      -5

   ....
201
   2001   23

and so on


How do I go about doing this? 我该怎么做呢?

I have a list of objects as mentioned above. 我有一个如上所述的对象列表。

I'm thinking of creating another class and them mapping to it but I'm perhaps making it more complicated than it needs to be 我正在考虑创建另一个类,并将它们映射到它,但我可能会让它变得比它需要的更复杂

public class pivot
{
        public string fund { get; set; }
        public List < pivotdetail >detail{ get; set; }
 }

public class pivotdetail
{
       pretty obvious
}




Any ideas on how I can do this or I should approach this? 关于我如何做到这一点的任何想法或我应该接近这个?

You're creating a grouping of a grouping. 您正在创建一个分组分组。 First, group at the deepest level, then group those groups going up levels to get the structure you want. 首先,在最深层次上进行分组,然后将这些群体分组,以获得您想要的结构。

from x in Data
group x.Amount by new { x.Fund, x.Account } into g
group new
{
    g.Key.Account,
    Amount = g.Sum(),
} by g.Key.Fund

Note that this will usually be inefficient as it will create new queries for every group. 请注意,这通常效率低下,因为它会为每个组创建新查询。 You might want to restrict it to a single grouping call on the database and further group in code. 您可能希望将其限制为对数据库的单个分组调用以及代码中的进一步分组。

from g in (from x in Data
          group x.Amount by new { x.Fund, x.Account } into g
          select new
          {
            g.Key.Fund,
            g.Key.Account,
            Amount = g.Sum()
          }).AsEnumerable()
group new
{
    g.Account,
    g.Amount,
} by g.Fund;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM