首页 > 解决方案 > 尝试使用 groupby 在 Linq lambda 语句中将值添加为 CSV

问题描述

我正在尝试以 CSV 形式在我的输出中获取凭证列表,例如 1,2,3,4

似乎无法弄清楚这 Vouchers = VoucherId , VoucherID 是我想要的

var paymentGroups = new List<PaymentGroups>();

paymentGroups = paymentVouchers
.GroupBy(x => new { x.PayFromBankAccountId, x.PaymentType}) 
.Select(x => new PaymentGroups
{
    PayFromBankAccountId = x.Key.PayFromBankAccountId,
    PaymentType = x.Key.PaymentType,
    TotalAmounts = x.Sum(z => z.TotalPaymentAmount), 
    TotalCount = x.Count(),
    //Group = x.Count()
    //Vouchers = x.All(y => y.VoucherId != null)
    //Vouchers = string.Join(y => y.
    //Vouchers = x.Sum(y => y.VoucherId.ToString())
    Vouchers =  VoucherId ,  VoucherID 
}).ToList();


var paymentVouchers = new List<PaymentVouchers>()
{

    new PaymentVouchers { PayFromBankAccountId = "ABC", PaymentType = 5, TotalPaymentAmount = 100, VoucherId = "1" },
    new PaymentVouchers { PayFromBankAccountId = "ABC", PaymentType = 5, TotalPaymentAmount = 200, VoucherId = "2" },
    new PaymentVouchers { PayFromBankAccountId = "ABC", PaymentType = 5, TotalPaymentAmount = 300, VoucherId = "3" },
    new PaymentVouchers { PayFromBankAccountId = "ABC", PaymentType = 6, TotalPaymentAmount = 100, VoucherId = "4" },
    new PaymentVouchers { PayFromBankAccountId = "ABC", PaymentType = 6, TotalPaymentAmount = 200, VoucherId = "5" },
    new PaymentVouchers { PayFromBankAccountId = "ABC", PaymentType = 6, TotalPaymentAmount = 300, VoucherId = "6" },
    new PaymentVouchers { PayFromBankAccountId = "DEF", PaymentType = 5, TotalPaymentAmount = 100, VoucherId = "7" },
    new PaymentVouchers { PayFromBankAccountId = "DEF", PaymentType = 5, TotalPaymentAmount = 200, VoucherId = "8" },
    new PaymentVouchers { PayFromBankAccountId = "DEF", PaymentType = 6, TotalPaymentAmount = 100, VoucherId = "9" },
    new PaymentVouchers { PayFromBankAccountId = "DEF", PaymentType = 6, TotalPaymentAmount = 200, VoucherId = "10" },
};

这是具有属性的类

public class PaymentGroups
{
    public Int32 Group {get; set;}
    public string PayFromBankAccountId { get; set; }
    public int PaymentType { get; set; }
    public decimal TotalAmounts { get; set; }
    public int TotalCount { get; set; }
    public string Vouchers {get; set;}
}

public class PaymentVouchers
{
    public string VoucherId {get; set;}
    public string PayFromBankAccountId { get; set; }
    public int PaymentType { get; set; }
    public decimal TotalPaymentAmount { get; set; }
}

标签: c#linqlambda

解决方案


您可以选择所有VoucherId并将它们与 连接起来string.Join,例如:

Vouchers = string.Join(",", x.Select(y => y.VoucherId ));

推荐阅读