Flame_Phoenix
Flame_Phoenix

Reputation: 17584

Create a C# dictionary from DB query with repeated keys

I have a Database with schools, and each school is in a City. Now I want to create a dictionary that contains all the cities of each schoool. To achieve this I tried this approach:

var schoolCities = schoolsWithAddresses.Where(school => school.Address.City != null).ToDictionary(sc => sc.Address.City.Name.ToLower());

Now, the problem with this is that a City can have multiple schools. So, when I create my dictionary, I end up with an exception "Repeated Key".

I want to create a dicitonary because it will allow me to make a very quick lookup on the cities that have schools (that is why I am not using a List, for example).

How do I overcome this problem in a way rhat allows me to still make efficient lookups?

Upvotes: 1

Views: 95

Answers (5)

Pravin Bakare
Pravin Bakare

Reputation: 174

try this

var schoolCities = schoolsWithAddresses
.GroupBy(x => x.city!=null)
.ToDictionary(x => x.Key, x => x.ToList());

Upvotes: 0

dav_i
dav_i

Reputation: 28107

I think what you want is a Lookup:

Represents a collection of keys each mapped to one or more values.

Example usage:

Lookup<string, School> schoolCities = schoolsWithAddresses
    .Where(school => school.Address.City != null)
    .ToLookup(school => school.Address.City);

IEnumerable<School> schoolsInLondon = schoolCities["London"];

Upvotes: 1

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

Something like this:

Dictionary<string, List<School>> schoolCities = schoolsWithAddresses
            .Where(school => school.Address.City != null)
            .GroupBy(school => school.Address.City)
            .ToDictionary(group => group.Key, group => group.ToList());

Upvotes: 1

MarkP
MarkP

Reputation: 4985

Use the ToLookUp extension method rather

var schoolCities = schoolsWithAddresses
.Where(school => school.Address.City != null)
.ToLookup(sc => sc.Address.City.Name.ToLower());

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 157018

You should group the items first, so that you have unique cities.

schoolsWithAddresses.Where(school => school.Address.City != null)
.GroupBy(s => s.Address.City, (k, v) => new { City = k, Schools = v })
.ToDictionary(d => d.City, e => e.Schools)
;

Upvotes: 1

Related Questions