猿问

如何在 linq 左连接查询中使用现有左模型预填充投影结果

假设我有以下代码(简化)使用带有左外连接的 linq to sql:


public class Program

{

    public static void Main()

    {       

        IList<Payment> paymentsList = new List<Payment>() { 

                new Payment() { ID = 1, Amount = 4 } ,

                new Payment() { ID = 2, Amount = -11 } ,

                new Payment() { ID = 3, Amount = 11 }

            };


        IList<Allocation> allocationList = new List<Allocation>() { 

                new Allocation(){ OriginalID = 1, ReversalID=2},

                new Allocation(){ OriginalID = 2, ReversalID=3}             

            };


        var summaryPayments = from s in paymentsList 

                            join alloc in allocationList on s.ID equals alloc.OriginalID into allocOrg

                            from po in allocOrg.DefaultIfEmpty()

                            join allocRev in allocationList on s.ID equals allocRev.ReversalID into allocRevs

                            from pr in allocRevs.DefaultIfEmpty()

                            select new Payment{Amount=s.Amount, ReversalId = (pr != null ? pr.ReversalID : 0)};


        foreach (var obj in summaryPayments)

        {


            Console.WriteLine("{0} - {1}", obj.Amount,obj.ReversalId);

        }


    }


}


public class Payment{


    public int ID { get; set; }

    public decimal Amount { get; set; } 

    public int? ReversalId { get; set; }    

}


public class Allocation{

    public int OriginalID {get;set;}

    public int ReversalID { get; set; } 

}


慕雪6442864
浏览 141回答 1
1回答

慕妹3146593

试试下面的代码&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var summaryPayments = (from s in paymentsList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;join alloc in allocationList on s.ID equals alloc.OriginalID into allocOrg&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;from po in allocOrg.DefaultIfEmpty()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;join allocRev in allocationList on s.ID equals allocRev.ReversalID into allocRevs&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;from pr in allocRevs.DefaultIfEmpty()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select new { s, pr }).Select(x => { x.s.ReversalId = (x.pr != null ? x.pr.ReversalID : 0); return x.s; });
随时随地看视频慕课网APP
我要回答