3

我有以下课程

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

我需要按 Linq 中的所有属性对它们进行分组,以便最后两个属性在分组结果中形成一个新字段。像这样:

        Group   Type    Status      InvoiceType          
        -------------------------------------------
        Group1  Online  New         Daily-Single
        Group2  Phone   Accepted    Daily-Single
        Group3  Store   Accepted    Weekly-Single
        Group3  Store   Accepted    Weekly-Bulk

这里的 InvoiceFreq 将是 Daily / Weekly 并且 InvoiceLevel = Single 或 Bulk。

到目前为止我的查询是这样的:

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

这当然不会给出预期的结果,因为这两个属性分别位于匿名类型中。

有没有办法在 Linq 中实现这一点?

4

2 回答 2

4

这应该有效:

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
    }; 
于 2012-10-22T07:32:04.110 回答
0

我不太确定 linq 的语法,但对于 lambda,我会使用它。如果您尝试对所有列进行分组,则基本上使用 distinct 。

Context.Booking.Distinct().Select(z=> new BookingSummaryLine { Group = z.Group, Type =        z.Type, Status = z.Status, InvType = (z.InvoiceFrequency + "-" + z.InvoiceLevel });
于 2012-10-22T07:48:46.307 回答