Reputation: 119
I have the following class
public class Booking
{
public string Group { get; set; }
public BookingType Type { get; set; }
public BookingStatus Status { get; set; }
public InvoiceFreq { get; set; }
public InvoiceLevel { get; set; }
}
That I'd need to group them by all properties in Linq so that the last two properties form one new field in the grouped result. Like this:
Group Type Status InvoiceType
-------------------------------------------
Group1 Online New Daily-Single
Group2 Phone Accepted Daily-Single
Group3 Store Accepted Weekly-Single
Group3 Store Accepted Weekly-Bulk
Here the InvoiceFreq will be Daily / Weekly and the InvoiceLevel = Single or Bulk.
The query I have so far is this:
var query = from b in Bookings
group b by new
{
b.Group,
b.Type,
b.Status,
b.InvoicingFrequency,
b.InvoicingLevel
} into bookingGroup
select new BookingSummaryLine()
{
Group = bookingGroup.Key.UserGroup,
Type = bookingGroup.Key.UserGroup,
Status = bookingGroup.Key.FinancialStatus,
InvType = String.Format({0}-{1},bookingGroup.Key.InvoicingFrequency, bookingGroup.Key.InvoicingLevel
};
This of course does not give the desired result as the two properties are in the anonymous type separately.
Is there any way to achieve this in Linq?
Upvotes: 3
Views: 2161
Reputation: 131
I'm not as sure about the syntax for linq but for lambda I would use this. Basically use distinct if your trying to group on all columns like that.
Context.Booking.Distinct().Select(z=> new BookingSummaryLine { Group = z.Group, Type = z.Type, Status = z.Status, InvType = (z.InvoiceFrequency + "-" + z.InvoiceLevel });
Upvotes: 0
Reputation: 5679
This should work:
var query = from b in Bookings
group b by new
{
b.Group,
b.Type,
b.Status,
InvType = String.Format({0}-{1},b.InvoicingFrequency, b.InvoicingLevel)
} into bookingGroup
select new BookingSummaryLine()
{
Group = bookingGroup.Key.UserGroup,
Type = bookingGroup.Key.UserGroup,
Status = bookingGroup.Key.FinancialStatus,
InvType = bookingGroup.Key.InvType
};
Upvotes: 4