using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
public static void Main()
var sw = new System.Diagnostics.Stopwatch();
var models = GetModels();
Console.WriteLine($"instantiate operation took => {sw.Elapsed}");
models = models.LeftOuterJoin(forms, (outter) => outter.ClientId, (inner) => inner.ClientId,
outter.referralForm = inner;
Console.WriteLine($"query operation took => {sw.Elapsed}{Environment.NewLine}");
Console.WriteLine($"Models Count {models.Count()}");
Console.WriteLine($"Models with null ReferralForm {models.Count(m => m.referralForm == null)}");
Console.WriteLine($"Models with ReferralForm instances {models.Count(m => !(m.referralForm == null))}");
static IEnumerable<ReferralModel> GetModels() => GetForms().Select(f => new ReferralModel { ClientId = f.ClientId })
.Concat(Enumerable.Range(0, 500).Select((idx) => new ReferralModel { ClientId = Guid.NewGuid() })).OrderBy(item => item.ClientId)
static IEnumerable<ReferralForm> _forms = Enumerable.Empty<ReferralForm>();
static IEnumerable<ReferralForm> GetForms()
if ((_forms?.Count() ?? 0) == 0)
_forms = Enumerable.Range(0, 500).Select((idx) => new ReferralForm { ClientId = Guid.NewGuid() }).ToHashSet();
public static class LinqExt
public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TKey> leftKey, Func<TRight, TKey> rightKey,
Func<TLeft, TRight, TResult> result)
return left.GroupJoin(right, leftKey, rightKey, (l, r) => new { l, r })
.SelectMany(o => o.r.DefaultIfEmpty(), (l, r) => new { lft = l.l, rght = r })
.Select(o => result.Invoke(o.lft, o.rght));
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; }