patterncsharpMinor
Is this the optimal way to write "find these IDs in a list of objects" using linq?
Viewed 0 times
thisthetheseoptimalobjectslinqidswaywriteusing
Problem
I've got a situation where I have a list of
Query
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 => ((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);Solution
Use a
Your code will then look like this:
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:
or this:
Dictionary 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 = ?Code Snippets
SELECT organization_id, division, name FROM organizations WHERE organization_id IN (?)SELECT organization_id, division, name FROM organizations JOIN user_organizations
USING (organization_id) WHERE user_id = ?Context
StackExchange Code Review Q#61268, answer score: 3
Revisions (0)
No revisions yet.