Get dictionary <int, string> from linq to object?
continuation of the problem How to get an array in linq for an object?
but now itβs not an array => Dictionary Type of city - Dictionary
var sites = (from country in db.Countries select new { Country = country.Title, Cities = country.Cities.Select(m => m.Title) }) .AsEnumerable() .Select(country => new SitiesViewByUser() { Country = country.Country, City = country.Cities.ToArray() }); update:
public class SitiesViewByUser { public string Country { get; set; } public Dictionary<int, string> City { get; set; } } You can use ToDictionary to create a dictionary from a LINQ sequence.
The first part is the key, and the second is the value, for example.
.Select(country => new SitiesViewByUser() { Country = country.Country, City = country.Cities.ToDictionary(c => c, c => c); }); This assumes that City on SitiesViewByUser is defined as Dictionary<string, string>
Your LINQ is pretty confusing. You create an anonymous type that is interrogated to form a Country , but which has the Country property on it that reports the Country Title (is this the name of the country?)
You also have a collection of Titles only cities, so I'm not sure what value you are going to use in your City dictionary for your type SitiesViewByUser .
Also, what is a City?: \
Update
You can do something like this:
var countries = (from country in db.Countries select new { Title = country.Title, CityIds = country.Cities.Select(c => c.Id), CityTitles = country.Cities.Select(c => c.Title) }).AsEnumerable(); // You have a collection of anonymous types at this point, // each type representing a country // You could use a foreach loop to generate a collection // of SitiesViewByUser, or you could use LINQ: var sitiesViewByUsers = countries.Select(c => new SitiesViewByUser { Country = c.Title, City = c.CityIds.Zip(c.CityTitles, (k, v) => new { Key = k, Value = v }) .ToDictionary(x => x.Key, x => x.Value) }; Alternatively, why don't you change the SitiesViewByUser type:
public class SitiesViewByUser { public string Country { get; set; } public IEnumerable<City> Cities { get; set; } } Then you can do (using free syntax):
var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser { Country = c.Title, Cities = c.Cities });