gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:57:20 24 4
gpt4 key购买 nike

假设我有以下代码(简化),使用 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; }
}

我工作了,但我想知道是否可以使用现有模型的属性预填充投影结果模型,而无需手动初始化所​​有这些模型,而只需填充“正确”集中的属性,例如。对于上述情况,我希望能够编写如下内容:

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 () {var model = s; model.ReversalId = (pr != null ? pr.ReversalID : 0);return model;};

最佳答案

试试下面的代码

            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 { s, pr }).Select(x => { x.s.ReversalId = (x.pr != null ? x.pr.ReversalID : 0); return x.s; });

关于c# - 如何在 linq 左连接查询中使用现有的左模型预填充投影结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53741633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com