I have two LINQ queries that I want to switch between depending upon the user's selection of a monthly report or yearly report. Before they were working but they were just giving the user a list of results sometimes with 8 of the same deal and instead I'd like to group them by the deal name and display a count of how many are in each group.
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);
After I do a selection like this I am having problems accessing columns within that selection that used to work when I just did a .ToList(); on the queries.
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++;
}
Anything after item. is not working I am wondering how I can access the elements of each item in the group and the count of how many items are in each group. Any help would be appreciated?
Each element in the result of a GroupBy
is a group - which itself then contains the elements, as well as a key. So you can do something like this:
foreach (var group in sponsorRedemptions)
{
Console.WriteLine("Group: {0}", group.Key);
foreach (var item in group)
{
Console.WriteLine(" {0}", item.PurchasedCardDeal.Deal.Vendor.Name);
}
}
As an aside, you only seemed to be using the PurchasedCardDeal.Deal
part after the Where
clause, so you might want to project to that:
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);
}
}
See more on this question at Stackoverflow