È 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
});
Qual è la definizione della proprietà City su SitiesViewByUser? – devdigital
Aggiornare il mio post – Mediator
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