Group by two properties as one in Linq
c#, linq
Solution
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
};
Problem
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?