0

Have a custom class named Company and I'm looking to get a single instance of this class returned based on a single Company.AccountID that I'm passing. I have most of the query, but I'm messing it up somewhere. Can someone help me out here?

Company cmp = Companies.Select(comp => comp.AccountID == accountID).Select(comp => new Company());

1
  • you should remove the class tag, it doesn't really.. suit the question
    – IEatBagels
    Jul 10, 2014 at 15:14

2 Answers 2

4

Use Enumerable.FirstOrDefault like:

Company obj = Companies.FirstOrDefault(comp=> comp.AccountID == accountID);

In your current query you are selecting result of a boolean operation. What you need is Where like:

Companies.Where(comp => comp.AccountID == accountID)

This will give you an IEnumerable<Company> object matching your condition, later you can add FirstOrDefault /First at the end of your query like:

Company c = Companies.Where(comp => comp.AccountID == accountID).FirstOrDefault();

Remember FirstOrDefault will return null, if no matching record is found. First on the other hand will throw an exception.

To select a single record from a collection, your options are First / FirstOrDefault, Single / SingleOrDefault , Last / LastOrDefault. (Last/LastOrDefault is only supported through LINQ to objects, it is not supported with Entity framework)

1
  • You may combine Where and First / FirstOrDefault: First(x=>x.AccountID == accountID)
    – Udontknow
    Jul 10, 2014 at 15:14
3

You have several options, you'll have to chose the best fit for you.

  1. Use First if you expect several matches based on your LINQ query but want an Exception thrown if there isn't at least one:

    var company = Companies.First(c => c.AccountID == accountID);
    
  2. Use FirstOrDefault if you expect several matches based on your LINQ query and want null if there are no matches.

    var company = Companies.FirstOrDefault(c => c.AccountID == accountID);
    
  3. Use Single if your query should return exactly one record. If there is any other result, an exception will be thrown.

    var company = Companies.Single(c => c.AccountID == accountID);
    
  4. Use SingleOrDefault if your query should return 0 or 1 record. If no record is found, null will be returned.

    var company = Companies.SingleOrDefault(c => c.AccountID == accountID);
    

Just be sure to make the right choice. Being specific with your choice of method now will express your intent to other developers in the future so that bugs don't slowly introduce themselves because of a query that was too generic.

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.