21

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);
0

1 Answer 1

51

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); 
2
  • I am. Perfect. Not sure why I didn't think of that :-) Thank you.
    – Nick
    Commented Oct 15, 2012 at 17:02
  • 1
    This worked great for me as well. We had to grab the first record in a 1 to many relationship. I added an .OrderBy as well to at least bring some sort of logic to the Take(1) method (so we get the first one alphabetically). Commented Jan 24, 2022 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.