Nick
Nick

Reputation: 5892

How can a LINQ join select only the first record?

I wish to select only the first record from the 'CustomerSubOwners' table in join query below and wondered what was the best way to achieve this in LINQ.

var result= (from t1 in db.Cases
             from t2 in db.CustomerSubOwners
                          .Where(o => t1.CustomerId == o.CustomerId && o.Expiry >= DateTime.Now)
                          .DefaultIfEmpty()
             select t1);

Upvotes: 21

Views: 27221

Answers (1)

Aducci
Aducci

Reputation: 26694

I think you are looking for the Take method like so:

var result= (from t1 in db.Cases
             from t2 in db.CustomerSubOwners.Where(o => t1.CustomerId == o.CustomerId && o.Expiry >= DateTime.Now)
                                            .Take(1)
                                            .DefaultIfEmpty()
             select t1); 

Upvotes: 51

Related Questions