开发者

Converting an IEnumerable list to a grouped list in Linq

I have a function that returns the following type:

 IEnumerable<开发者_如何学JAVA;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.


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜