2012-02-26 12 views
7

continuazione del problema How get array in linq to entity?Ricevi il dizionario <int, string> da linq all'entità?

ma ora non è gamma => dizionario tipo City è dizionario

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

aggiornamento:

public class SitiesViewByUser 
    { 
     public string Country { get; set; } 
     public Dictionary<int, string> City { get; set; } 
    } 
+0

Qual è la definizione della proprietà City su SitiesViewByUser? – devdigital

+0

Aggiornare il mio post – Mediator

+0

Da dove proviene la chiave int del dizionario? È questa la chiave primaria della città? Non stai recuperando questo nella query LINQ iniziale alle entità. – devdigital

risposta

9

È possibile utilizzare ToDictionary per creare un dizionario da un Sequenza LINQ.

La prima parte è la chiave e la seconda il valore, ad es.

.Select(country => new SitiesViewByUser() 
{ 
    Country = country.Country, 
    City = country.Cities.ToDictionary(c => c, c => c); 
}); 

Questo presuppone che City su SitiesViewByUser è definito come Dictionary<string, string>

tuo LINQ è piuttosto confusa però. Stai creando un tipo anonimo, creato per modellare un Country, ma che ha una proprietà Country su di esso, che è infatti il ​​Title del paese (è il nome del paese?).

Hai anche una raccolta di solo la città Titles, quindi non sono sicuro del valore che utilizzerai nel tuo dizionario City sul tuo tipo SitiesViewByUser.

Inoltre, cos'è un Sitie? : \

Aggiornamento

Si potrebbe fare qualcosa di simile:

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

In alternativa, perché non si cambia il tipo SitiesViewByUser essere:

public class SitiesViewByUser 
{ 
    public string Country { get; set; } 
    public IEnumerable<City> Cities { get; set; } 
} 

Poi si può fare (usando sintassi fluente):

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

Ho aggiornato il mio post – Mediator

Problemi correlati