如何访问使用groupBy的LINQ查询中的元素?

时间:2015-06-30 20:11:10

标签: c# sql linq

我想要切换两个LINQ查询,具体取决于用户选择的月度报告或年度报告。在他们工作之前,他们只是给用户一个结果列表,有时候有8个相同的交易,而是我想按交易名称对它们进行分组,并显示每个组中有多少个。

var sponsorRedemptions = db.PurchasedCardDealRedemptions.Where(pcdr => pcdr.PurchasedCardDeal.PurchasedCard.Card.WhiteLabelId == whiteLabelId)
    .Where(pcdr => pcdr.RedemptionDate.Year == year)
    .Where(pcdr => pcdr.RedemptionDate.Month == month)
    .OrderBy(pcdr => pcdr.PurchasedCardDeal.Deal.Vendor.Name)
    .GroupBy(pcdr => pcdr.PurchasedCardDeal.Deal.Name);


var yearponsorRedemptions = db.PurchasedCardDealRedemptions.Where(pcdr => pcdr.PurchasedCardDeal.PurchasedCard.Card.WhiteLabelId == whiteLabelId)
      .Where(pcdr => pcdr.RedemptionDate.Year == year)
      .OrderBy(pcdr => pcdr.PurchasedCardDeal.Deal.Vendor.Name)
      .GroupBy(pcdr => pcdr.PurchasedCardDeal.Deal.Name);

在我做了这样的选择后,我在访问该选择中的列时遇到了问题,当我刚刚执行了.ToList()时,该列已经过去了。关于查询。

foreach (var item in sponsorRedemptions)
{
    csv.Append("\n");

    csv.Append(item.PurchasedCardDeal.PurchasedCard.Card.Name + ", " + item.PurchasedCardDeal.Deal.Vendor.Name + ", " + item.PurchasedCardDeal.Deal.Name);

    totalRedemptions++;
}

项目之后的任何事情。我不知道如何访问组中每个项目的元素以及每个组中的项目数。任何帮助将不胜感激?

2 个答案:

答案 0 :(得分:5)

GroupBy结果中的每个元素都是一个组 - 它本身包含元素和键。所以你可以这样做:

foreach (var group in sponsorRedemptions)
{
    Console.WriteLine("Group: {0}", group.Key);
    foreach (var item in group)
    {
        Console.WriteLine("  {0}", item.PurchasedCardDeal.Deal.Vendor.Name);
    }
}

顺便说一下,你似乎只是在PurchasedCardDeal.Deal子句之后使用Where部分,所以你可能想要投射到那个:

var sponsorRedemptions = db.PurchasedCardDealRedemptions
    .Where(pcdr => pcdr.PurchasedCardDeal.PurchasedCard.Card.WhiteLabelId == whiteLabelId)
    .Where(pcdr => pcdr.RedemptionDate.Year == year)
    .Where(pcdr => pcdr.RedemptionDate.Month == month)
    .Select(pcdr => pcdr.PurchasedCardDeal.Deal);
    .OrderBy(deal => deal.Vendor.Name)
    .GroupBy(deal => deal.Name);

foreach (var group in sponsorRedemptions)
{
    Console.WriteLine("Group: {0}", group.Key);
    foreach (var deal in group)
    {
        Console.WriteLine("  {0}", deal.Vendor.Name);
    }
}

答案 1 :(得分:1)

item是该组中元素的集合。

要查看按您分组的内容,请使用item.Key。要查看单个项目,请使用访问集合的常规方法,例如循环或LINQ方法(例如,Count())。