chint
chint

Reputation: 47

Linq - where condition on child table

can we apply where condition on a column in child table in below query ?

Patient is main table and i need to supplement below where condition with a column in Assess table like

Where(a => a.Date >= startdate && a.Date < stopdate && a.patient.assess.column1 == 10)

full query

  => dc.Patient
        .Include("first")
        .Select(a => new
        {
            Patient = a,
        Date = a.Assess.Max(x => x.Date),
        M3 = a.M3,
        Assess = a.Assess,
        Details = a.Assess
                    .Select(x => new
            {
                x.Key,
            x.Team
            })
        })
        .Where(a => a.Date >= startdate && a.Date < stopdate)
        .OrderBy(a => a.Date)
        .Take(batchSize)
        .ToList()
    );

Upvotes: 1

Views: 2405

Answers (1)

Igor
Igor

Reputation: 62308

You can use additional sub/embedded lambda statements within a lambda. In this case the IEnumerable.Any statement can be referenced inside the Where statement. Any will return true if there is any condition that matches the lambda and can be called as Assess is a collection.

My assumptions were:

  • Assess is a strongly typed collection
  • You wanted any the Where clause to match if there were any Assess instances in the collection where the property column was equal to the value of 10

Code:

=> dc.Patient
    .Include("first")
    .Select(a => new
    {
        Patient = a,
        Date = a.Assess.Max(x => x.Date),
        M3 = a.M3,
        Assess = a.Assess,
        Details = a.Assess.Select(x => new
        {
            x.Key,
            x.Team
        })
    })
    .Where(a => a.Date >= startdate && a.Date < stopdate && a.Assess.Any(ass => ass.column1 == 10))
    .OrderBy(a => a.Date)
    .Take(batchSize)
    .ToList()
);

Upvotes: 4

Related Questions