views:

46

answers:

2

I have a function that returns the following type:

 IEnumerable<IGrouping<String, ExportTransaction>>

In this function I create a list of the following type, using a linq expression:

  IEnumerable<ExportTransaction>

The Linq code looks like this:

 IEnumerable<ExportTransaction> transactions = ctx.ExportTransactions
                                                  .Where(x => x.Id != null);

How can I convert “transactions” to a grouped list of the type shown at the top of this page. The function does various things with the “transactions” so It must stay as “IEnumerable” inside the function but must be converted to the grouped list when returned.

+1  A: 

I'll assume that the Transactions have a name property and that's what you want to group the Transactions by. If that's not the case, all you have to do is change the property in the GroupBy call:

var transactions = ctx.ExportTranactions
                      .Where(x => x.Id != null)
                      .GroupBy(x => x.Name);
Justin Niessner
The function calls out to other functions to do different types of grouping. If no grouping is required I need to return the “transactions” as a grouped list but no grouping should be applied – if that makes sense.
Retrocoder
@Retrocode - If that's the case, then you should have two different methods. One that is called if grouping is required that returns `IEnumerable<IGrouping<string, ExportTransaction>>` and another that doesn't group and returns `IEnumerable<ExportTransaction>`.
Justin Niessner
Quite right of course. I've split the function into two methods which fixed part of my problem. Many thanks.
Retrocoder
A: 

Does it really need to be grouped and if so what do you want to group it by? It sounds to me like you have your data set and you could be trying to force it into a format you don't necessarily need.

Typically to group a data set you'd do something like:

var grouping = ctx.ExportTransactions.Where(x => x.Id != null)
                                     .GroupBy(x => x.Description);

That would create an IEnumerable<IGrouping<string, ExportTransaction>> grouping all the transactions with an identical description, presuming that each transaction had description.

If you need all the records in a single group you can always do the following:

    var grouping = ctx.ExportTransactions.Where(x => x.Id != null)
                                     .GroupBy(x => string.Empty);

Which will give you what you need with the group key being an empty string, but I'd strongly advise against it and instead suggest looking at why you need to return a grouping when you don't seem to want to group by anything.

Dave