访问列表中与 GroupBy() 项目相关的项目

Access items in list pertaining to GroupBy() item

我正在实例化 List,派生自 ObservableCollection:

var paidTrips = PaidTrips
    .GroupBy(p => new {p.LicenseHolderID})
    .ToList();

通过 foreach 循环,我可以访问 LicenseHolderID.

中的各种不同值
foreach (var licenseHolder in paidTrips) {
    // accessing the string value of LicenseHolderID
    // but no access to the other items
}

我需要帮助:

我如何才能访问 paidTrips 中属于 LicenseHolderID 的其他项目? (原因:我正在创建发票,每个 LicenseHolderID 一张,并且我正在使用所有其他集合属性 中的数据构建发票)。

为了提供一些背景信息,这是我正在使用的完整系列:

PaidTrips.Add(new PaidTrip {

    LicenseHolderID = dr[0].ToString(),
    VehicleID = dr[1].ToString(),
    Year = dr[2].ToString(),
    Month = dr[3].ToString(),
    Payment = (decimal)dr[4],
    PaymentNet = (decimal)dr[5],
    OrderFee = (decimal)dr[6],
    PaymentFee = (decimal)dr[7],
    TripVATcode = (decimal)dr[8],
    LicenseHolderInvoiceID = dr[9].ToString(),
    TripFeeNet = (decimal)dr[10],
    TripFeeVATcode = (decimal)dr[11],
    RidelRegionInvoiceID = dr[12].ToString(),
});

如果我没理解错的话,你想访问每个组成员的 属性。为此,您应该使用嵌套的 foreach 来遍历每个组并访问其成员。

    var PaidTrips = new List<PaidTrip>();

    var paidTrips = PaidTrips
        .GroupBy(p => new { p.LicenseHolderID })
        .ToList();

    foreach (var group in paidTrips)
    {
        var licenseHolderID = group.Key.LicenseHolderID;

        foreach (var paidTrip in group.ToList())
        {
            Console.WriteLine(paidTrip.TripFeeNet);
        }
    }
foreach (var licenseHolder in paidTrips) {
    // accessing the string value of LicenseHolderID
    if (licenseHolder.Key == desiredLicenseHolderID){
       foreach (var paidItem in licenseHolder){
          paidItem.VehicleID = .......
       }
    }        
}

.GrouBy() Returns 一个 IGrouping 对象,它包含键和按键分组的元素。要访问您在遍历项目并找到一个之后的 Key 分组的元素,您可以简单地以数组形式遍历该项目。

这取决于您希望如何处理每张发票的数据?您是否希望汇总每个 LicenseHolderID 组中的数据?

var PaidTrips = new List<PaidTrip>();

var paidTrips = PaidTrips
    .GroupBy(p => new { p.LicenseHolderID })
    .ToList();

foreach (var group in paidTrips)
{
    var licenseHolderID = group.Key.LicenseHolderID;
    
    //ie here total payment (This sums all payments for this LicenseHolderID)
    var totalPayment = group.Sum(x => x.Payment)

   // count of payments made (This Counts all Payments greater than 0)
   var totalPayments = group.Count(x => x.Payment > 0)

   //Use variables in your invoice generation
  
}

或如上遍历每个组项并以单数形式访问它。