获取Grouping Linq之外的参数

时间:2015-06-18 17:30:35

标签: c# .net winforms linq

我需要使用linq从集团中获取一些Field,例如,这是我的代码:

(from PaymentTypes in PaymentTypes_DataTable.AsEnumerable()
join CashTransactions in CashTransactions_DataTable.AsEnumerable()
    on PaymentTypes.Field<Int32>("cashpaymenttype_id")
    equals CashTransactions.Field<Int32>("cashpaymenttype_id")
    into JoinedCashTransactions
from CashTransactions in JoinedCashTransactions.DefaultIfEmpty()
group CashTransactions by PaymentTypes.Field<Int32>("cashpaymenttype_id")
into GroupPaymentTypes
select new
{
    cashpaymenttype_id = 0, // Get PaymentTypeID
    cashpaymenttype_name = "", // Get PaymentTypeName
    cashtransaction_amount = GroupPaymentTypes.Sum(a =>
       a != null
          ? (a.Field<Int32>("cashtransactionstatus_id") == 1 ||
            a.Field<Int32>("cashtransactionstatus_id") == 3 ? 1 : -1) *
            a.Field<Double>("cashtransaction_amount") 
          : 0.00),
}).Aggregate(PaymentTypesTransactions_DataTable, (dt, result) => { 
    dt.Rows.Add(result.cashpaymenttype_id, result.cashpaymenttype_name,
   result.cashtransaction_amount); return dt; });

此linq有效,但我需要获取cashpaymenttype_idcashpaymenttype_name字段PaymentTypes

1 个答案:

答案 0 :(得分:1)

假设PaymentTypeID - PaymentTypeName为1对1,您可以将您的组更改为:

group CashTransactions by new 
{ 
    PaymentTypeId = PaymentTypes.Field<Int32>("cashpaymenttype_id"),
    PaymentTypeName = PaymentTypes.Field<String>("cashpaymenttype_name")
}
into GroupPaymentTypes

您的选择将如下所示:

select new
{
    cashpaymenttype_id = GroupPaymentTypes.Key.PaymentTypeId, 
    cashpaymenttype_name = GroupPaymentTypes.Key.PaymentTypeName, 
    ...
}