如果有2个不同的分组,如何使用groupBy?

时间:2012-01-20 23:35:40

标签: c# linq group-by

我有这个样本数据

1/14/2012,5,Gas
1/15/2012,5,Gas
1/16/2012,5,Gas
1/17/2012,5,Gas
1/18/2012,5,Gas
1/19/2012,5,Gas
1/20/2012,5,Gas
1/21/2012,5,Gas
1/22/2012,5,Gas
1/23/2012,5,Gas
1/24/2012,5,Gas
1/25/2012,5,Gas
1/26/2012,5,Gas
1/27/2012,5,Gas
1/28/2012,5,Gas
1/29/2012,5,Gas
1/30/2012,5,Gas
1/31/2012,5,Gas
02/01/2012,5,Gas

有时我想按“月”和“年”分组,有时我只想按“年”分组

  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 TransactionsGroupedByMonthYear { Month = x.TransactionDate.Month, Year = x.TransactionDate.Year });
        break;
    case DollarCapPeriod.Yearly:
  groupTransactions = filterdTransactions.GroupBy(x => new TransactionsGroupedByMonthYear { Month = 0, Year = x.TransactionDate.Year });
        break;
    default:
        break;
}


public class TransactionsGroupedByMonthYear
    {
        public int Month { get; set; }
        public int Year { get; set; }

    }

上面的代码是我到目前为止所拥有的。第一个月有效。这是失败的第一年。我正在尝试使用混凝土玻璃进行分组,但它无法正常工作。有人告诉我将Month设置为零,基本上让它忽略Month并将其分组,好像它只是使用年份但是不起作用。

当它们将它们分组时,它只将它们分成19组(每个记录基本上一组)。当我查看调试器时,我看到了像这样的数据

   foreach (var group in groupTransactions)
            {
                var key = group.Key;
                int Month = key.Month;
                int Year = key.Year;
                System.Diagnostics.Debug.WriteLine("Month: {0}, Year: {1}", Month, Year);
            }

结果

Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012
Month: 0, Year: 2012

当它只是1条记录时,所有这些记录都已分组。因为它们都来自2012年

修改

Scott Rippey - 我试过你给的东西,但我仍然没有工作。

 groupTransactions = filterdTransactions.GroupBy(
                            // Key selector:
                            x => x.TransactionDate.Year,
                            // result selector:
                            (year, items) => new TransactionsGroupedByMonthYear{ Year = year, Month = 0, Transactions = items});


public class TransactionsGroupedByMonthYear
{
    public int Month { get; set; }
    public int Year { get; set; }
    public IList<TransactionDto> Transactions { get; set; }

}

Error   1   Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<int>' because it is not a delegate type      

修改2

我刚注意到你有item.toList()

现在我明白了

Error   1   Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<CCRecomendator.Framework.Domain.DTO.TransactionsGroupedByMonthYear>' 
                                        to 'System.Collections.Generic.IEnumerable<System.Linq.IGrouping<CCRecomendator.Framework.Domain.DTO.TransactionsGroupedByMonthYear,CCRecomendator.Framework.Domain.DTO.TransactionDto>>'. An explicit conversion exists (are you missing a cast?)

所以我看到的问题是这会返回不同的类型。我需要使用“Month”和“Yearly”切换分组代码来返回相同的数据类型(否则我只会使用匿名类型)。

1 个答案:

答案 0 :(得分:1)

为什么GroupBy无法正常工作

TransactionsGroupedByMonthYear不会覆盖相等运算符,因此GroupBy将使用参考比较 - 换句话说,没有两个{{}比较时1}}会相等。

最简单的解决方案是执行您在第一个示例中所做的操作...而是使用匿名对象。匿名对象会自动覆盖相等运算符,它们非常适合TransactionsGroupedByMonthYear运算。

否则,您必须覆盖GroupBy课程中的.Equals.GetHashCode方法。

您为什么使用GroupBy?

您实际上每年需要列表的分组项目吗?如果您只想获得明确的年份列表,则不应使用TransactionsGroupedByMonthYear,而应使用GroupBy

根据Distinct的名称判断,我看到TransactionsGroupedByMonthYearMonth,但我猜你应该也有Year属性。如果这是真的,那就继续阅读。

您的代码似乎正在尝试输出存储在Transactions中的已分组项目列表
为此,您应该使用以下重载:GroupBy(keySelector, resultSelector)

基本上,这种重载允许您对每个匹配的组执行某些操作 - 例如创建TransactionsGroupedByMonthYear

TransactionsGroupedByMonthYear

回复:编辑2

您在编辑2 中看到错误的原因是因为以下行:

groupTransactions = filterdTransactions.GroupBy(
    // Key selector:
    x => new { x.Year },
    // result selector:
    (key, items) => new TransactionsGroupedByMonthYear{ Year = key.Year, Month = 0, Transactions = items.ToList()})
);

应该是:

IEnumerable<IGrouping<TransactionsGroupedByMonthYear, TransactionDto>> groupTransactions = null;

你只是宣称它是错误的类型。