tags:

views:

582

answers:

1

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  A: 

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!

Kirk Broadhurst
Pretty cool. I like the nested calculators. So I am thinking that each named time frame the customer selects would be a separate collection like you have above in "groups", then join the collections together based on the EventName?
Dr. Zim
Kirk Broadhurst