Group by two properties as one in Linq

断了今生、忘了曾经 提交于 2021-02-09 12:38:09

问题


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?


回答1:


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
    }; 



回答2:


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 });


来源:https://stackoverflow.com/questions/13006600/group-by-two-properties-as-one-in-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!