Search code examples
entity-frameworklinq-to-entities

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


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; }
    }

Solution

  • 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; }
        public IEnumerable<City> Cities { get; set; }
    }
    

    Then you can do (using fluent syntax):

    var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser
      {
        Country = c.Title,
        Cities = c.Cities
      });