Is this the optimal way to write "find these IDs in a list of objects" using linq? 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; }
}


Query

vm.locations = _organizations.GetOrganizations().Where(o =&gt; ((ApplicationUser)User).OrganizationIdList.Any(u =&gt; u == o.Id)).Select(org =&gt;
    new SelectListItem
    {
        Text = org.Division + " - " + org.Name,
        Value = org.Id.ToString()
    }).OrderBy(item =&gt; item.Text);
Use a Dictionary&lt;int, Organization&gt; to look up organizations by their IDs quickly.

Your code will then look like this: OrganizationIdList.Select(id =&gt; 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 = ?