I have this code
// was before var groupTransactions;
IEnumerable<IGrouping<TransactionsGroupedByMonthYear, TransactionDto>> groupTransactions = null;
DollarCapPeriod dollarCapPeriod = (DollarCapPeriod)Enum.Parse(typeof(DollarCapPeriod), reward.DollarCapPeriod);
switch (dollarCapPeriod)
{
case DollarCapPeriod.Monthly:
groupTransactions = filterdTransactions.GroupBy(x => new { x.TransactionDate.Month, x.TransactionDate.Year });
break;
case DollarCapPeriod.Yearly:
groupTransactions = filterdTransactions.GroupBy(x => new TransactionsGroupedByMonthYear { Month = 0, Year = x.TransactionDate.Year });
break;
default:
break;
}
I want to do something like that but it wants the type initialized. So I am wondering is there away around this or do I have to make some sort of concrete type? If so how do I do it again with groupBy?
Sample Data
1/14/2012,5,Gas
1/15/2012,5,Gas
1/16/2012,5,Gas
1/17/2012,5,Gas
Edit
Currently I am trying to do now use a concrete backing but I need to filter by 2 different ways. Sometimes I need only the “Year” and some times I need “Month” and “Year”
I don’t know how to do this. They both need to go in the same variable so they need to be the same type.
First of all, don’t confuse anonymous types with inferred types. The
varkeyword does not necessarily mean a type is anonymous. An anonymous type does not have a name as far as the developer is concerned (the compiler, of course, gives it one, but that’s an implementation detail that you can and should ignore). An inferred type, using thevarkeyword, could have a name, you just didn’t have to type it.It is never allowed to say:
because there is no information from which to infer the type.
In the general case, you can use anonymous types in scoping situations like loops, try/catch, etc. by initializing a new instance of the anonymous type ahead of time:
As long as the field names and types match between the two anonymous type initializers, the “actual” type is the same.
In your specific case, though, you don’t want just an anonymous type, because
GroupBydoesn’t returning an anonymous type. It returns anIEnumerable<IGrouping<TKey, TSource>>, and in your case onlyTKeyis anonymous. While it is possible to declare that type in code, it’s very hard, and would involve temporary variables being declare solely to get their anonymoustypeof()information out of them. It would almost certainly be an unmaintainable mess.Instead you should just declare a type to use at your group key. It’s still going to be ugly, on account of the nested generics, but nowhere near as bad as trying to use the anonymous type.
and get your grouping: