Alex Rivera | Logout

Receive Dictionary<int, string> from linq to entity?

Asked 2012-02-26T14:58:32.420
10

continuation of the issue How get array in linq to entity?

but now is not array => Dictionary City type is 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; }
    }
Edit
Report

1 Answer

14

You can use ToDictionary to create a dictionary from a LINQ sequence.

The first part is the key, and the second the value, E.g.

.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 quite confusing though. You are creating an anonymous type, asssumed to shape a Country, but which has a Country property on it, which is infact the Title of the country (is that the name of the country?).

You also have a collection of just the city Titles, so I'm not sure what value you are going to use in your City dictionary on your SitiesViewByUser type.

Also, what is a Sitie? :\

Update

You could 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 to be:

public class SitiesViewByUser
{
    public string Country { get; set; }
 
answered 2012-02-26T15:04:20.067

Your Answer