Linq: How to transform rows to columns with a count (Crosstab data)?

只愿长相守 提交于 2019-12-20 02:38:24

问题


I think I need a way to perform a pivot or crosstab using C# and Linq with an indeterminate number of columns. However, I will add some beginning detail to see where it goes.

< Beginning detail >

Imagine a table that has two fields:

string EventName;
Datetime WhenItHappend;

We want to generate a report like the example below where we group by the EventName, then have a series of columns that calculate some date and time frame count. The difficulty is obviously a variable number of columns.

  Sport   Jan 2010Jan 2009Feb 2010Feb 2009
Basketball    26      18      23      16  
Hockey        28      19      25      18  
Swimming      52      45      48      43  

The customer can create any number of named event counters for a report. The functions are always the same: "Name", "begin", "end".

Any way to assemble this as a single linq IQueryable result in C#?

< End Beginning detail >

As far as SQL goes, I tried creating a date range table {TimeFrameName, begin, end} and joined that to the above table where begin <= whenItHappened and whenItHappened <= end, which produced a nice set of {EventName, TimeFrameName} then did a count(*), but was still left with how to transform the data, making the rows in to columns.


回答1:


You have a class / SQL row

class Thing
{
    public string EventName;
    public DateTime WhenItHappend;
}

and you want to group by EventName and WhenItHappened.Month

// make a collection and add some Things to it
var list = new List<Thing>();
list.Add(new Thing(){ .... });
// etc

var groups = list.GroupBy(t => new { t.WhenItHappend.Month, t.EventName } );

Now you essentially have a 2 dimensional array of collections. You can iterate through these on Month / EventName to get the counts of the items in each collection, which is what you want to display in your table.

foreach (var row in groups.GroupBy(g => g.Key.EventName))
{
    foreach (var month in row.GroupBy(g => g.Key.Month))
    {
        var value = month.Count();
    }
}

The GroupBy operator returns a collection of groups, where each group contains a Key and a subset of the original list that match the specified Key. If you specify a 2 dimensional Key, you can treat the result as a 2 dimensional array of collections.

GroupBy is a very powerful operator!



来源:https://stackoverflow.com/questions/2405249/linq-how-to-transform-rows-to-columns-with-a-count-crosstab-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!