1/13/2022 5:18:04 PM

If you have to search through a large List in .NET by a specific shared field, you can speed things up by create a Linq Lookup object. This acts like a Dictionary allowing you to define a key and get the related items to that key.


//simple model/entity
public class User
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public string Email { get; set; }
	public string Address_State { get; set; }
}


//sample data, list of users
var users = new List<Entities.User>()
{
	new Entities.User()
	{
		Address_State = "New York",
	},
	new Entities.User()
	{
		Address_State = "New York",
	},
	new Entities.User()
	{
		Address_State = "New York",
	},
	new Entities.User()
	{
		Address_State = "Florida",
	},
	new Entities.User()
	{
		Address_State = "Texas",
	},
	new Entities.User()
	{
		Address_State = "Texas",
	},
	new Entities.User()
	{
		Address_State = "Texas",
	},
};


//create a lookup based on the Address_State field
//the key is the state name, the value is a list of users with that state
Lookup<string, Entities.User> lookup_by_address_state = (Lookup<string, Entities.User>)users.ToLookup(x => x.Address_State, x => x);

//list all keys in the lookup
var states = lookup_by_address_state.Select(x => x.Key).ToList();

//get users by key/address state
foreach (var state in states)
{
	var users_by_state = lookup_by_address_state[state].ToList();
	foreach (var user in users_by_state)
	{
	}
}

//iterate over all entries/keys in the lookup
foreach (var kvp in lookup_by_address_state)
{
	var users_by_state = kvp.ToList();
	foreach (var user in users_by_state)
	{
	}
}