.... ou comment créer un dictionnaire de "regroupement" a partir d'une liste simple.
Au départ on a en entrée : List<Communes> lesCommunes.
Et on voudrait créer un dictionnaire de ces meme communes ayant pour clé leur code postal. MAIS.... plusieurs communes pouvant avoir le meme code postal, on souhaiterait avoir en valeur non pas une Commune, mais une liste de communes. Autrement dit :
> Dictionary<string, List<Commune>>
Ceci se fait via la requête suivante en utilisant la méthode d'extension ToDictionary<TKey, TSource>(...) :
var rqt = from c in lesCommunes
group c by c.CodePostal into communes_par_CP
select new { list = communes_par_CP };
Dictionary<string, List<Commune>> lesCommunesParCodePostal = rqt.ToDictionary(a => a.list.Select(b => b.CodePostal).First(), c => c.list.Select(y => y).ToList<Commune>());
Et tant qu'à faire, autant pousser jusqu'au SortedDictionary....:
SortedDictionary<string, List<Commune>> lesCommunesParCodePostal = new SortedDictionary<string, List<Commune>>(rqt.ToDictionary(a => a.list.Select(b => b.CodePostal).First(), c => c.list.Select(y => y).ToList<Commune>()));