I've got a situation where I have a list of Organizations (code to follow), and a user has a list of OrganizationIds (ints). I want to filter down the full list of Organizations using the User's OrganizationId list for a dropdown list. The query works, but it feels like there may be a more optimal way to write it. Is there, or am I already pretty much optimized?

public class Organization
    public int Id { get; set; }
    public string Division { get; set; }
    public bool IsActive { get; set; }
    public bool IsDefault { get; set; }
    public string Name { get; set; }


vm.locations = _organizations.GetOrganizations().Where(o => ((ApplicationUser)User).OrganizationIdList.Any(u => u == o.Id)).Select(org =>
    new SelectListItem
        Text = org.Division + " - " + org.Name,
        Value = org.Id.ToString()
    }).OrderBy(item => item.Text);
| improve this question | | | | |

Use a Dictionary<int, Organization> to look up organizations by their IDs quickly.

Your code will then look like this: OrganizationIdList.Select(id => organizations[id])....

Given your clarification in the comments that your are getting organizations from a database, you should let the database do the hard work for you. The code will depend upon the ORM you're using, but a relatively SQL-agnostic version of the query will look like this:

SELECT organization_id, division, name FROM organizations WHERE organization_id IN (?)

or this:

SELECT organization_id, division, name FROM organizations JOIN user_organizations
USING (organization_id) WHERE user_id = ?
| improve this answer | | | | |
  • \$\begingroup\$ GetOrganizations() returns a List<Organization> -- wouldn't the conversion to a Dictionary be more intensive? (I agree this is clearer and cleaner, though!) \$\endgroup\$ – pennstatephil Aug 27 '14 at 22:36
  • \$\begingroup\$ @pennstatephil can you change GetOrganizations? Do the organizations change over time? Are they coming from a database? It's hard to recommend what to do without more context. \$\endgroup\$ – mjolka Aug 27 '14 at 22:39
  • \$\begingroup\$ they are indeed coming from a DB. while changes are not likely to happen often, they can occur. \$\endgroup\$ – pennstatephil Aug 27 '14 at 22:41
  • \$\begingroup\$ @pennstatephil then you should let the db do the work for you. Either select from organizations where organization_id in ... Or select from organizations join users using organization_id where user_id = ... \$\endgroup\$ – mjolka Aug 27 '14 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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