简体   繁体   English

如何通过 Id Key 字段将两个列表合并为一个模型?

[英]How to combine two lists into one Model by an Id Key field?

I have a model that looks like this我有一个看起来像这样的模型

public class ReferralModel
{
    public string? ClientName { get; set; }
    public Guid? ClientId { get; set; }
    public string? ClientNumber { get; set; }
    public string? ClientDOB { get; set; }
    public string? DateSubmitted { get; set; } = default;
    public DateTime? ModifiedDateSubmitted { get; set; }
    public string? ReportStatus { get; set; }
    public string? ReferralNotes { get; set; }
    public ReferralForm? referralForm { get; set; }
}

public class ReferralForm
{
    public Guid FileId { get; set; }
    public Guid ClientId { get; set; }
    public string? Name { get; set; }
    public string? FileName { get; set; }
    public string? ContentType { get; set; }
    public string? FileExtension { get; set; }
    public byte[]? FileContent { get; set; }
    public DateTime CreatedDate { get; set; }
}

I have two separate lists that both have the same ClientId.我有两个单独的列表,它们都具有相同的 ClientId。

var referrals = new List<ReferralModel>();
var referralForms = new List<ReferralForm>();

I want to add the referral forms list to its corresponding ReferralList so that each referral list will have the correct Referral form (ReferralForm? referralForms).我想将推荐表格列表添加到其相应的 ReferralList 中,以便每个推荐列表都有正确的推荐表格(ReferralForm?referralForms)。

referrals.referralForm = referralForms.Where(x => x.ClientId == referrals.ClientId);

I thought about looping through each of the list of referrals, but the list could be in the thousands and that seems like it would take too much time.我考虑过遍历每个推荐列表,但列表可能有数千个,这似乎会花费太多时间。 This has to be almost instant mapping这几乎是即时映射

I'll provide a general approach here -- using an Extension Method LeftOuterJoin (in respect to Enumerable.Join<TOuter,TInner,TKey,TResult> , but as LEFT OUTER JOIN behavior)我将在这里提供一种通用方法——使用扩展方法LeftOuterJoin (关于Enumerable.Join<TOuter,TInner,TKey,TResult> ,但作为LEFT OUTER JOIN行为)

It would look something like this:它看起来像这样:

var models = GetModels().LeftOuterJoin(GetForms(), 
  (outter) => outter.ClientId, 
  (inner) => inner.ClientId, 
  (outter, inner) => {
    outter.referralForm = inner;
    return outter
  });

dotnetFiddle点网小提琴

Edit编辑

replacing Enumerable.Join with Extension LeftOuterJoin usage -- as referenced in popular SO Answer https://stackoverflow.com/a/39020068/1366179将 Enumerable.Join 替换为扩展LeftOuterJoin用法——如流行的 SO Answer https://stackoverflow.com/a/39020068/1366179中所引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM