简体   繁体   中英

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.

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).

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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