c# - Converting object property values to dictionary -


lets say, have list of objects

public class room{     public string name {get; set;}     public int[] userid {get; set;} } 

what efficient way of converting list dictionary following

dictionary<int, list<string>>  

where key userid , string name of room. in advance.

i use linq's aggregate method shown below. (note took liberties original object list vs array demo, can change that).

var names = new list<room>() {     new room() { name = "alpha", userid = new list<int> { 10, 40 }},     new room() { name = "omega", userid = new list<int> { 10, 20, 30 }}, };  // aggragate needs item pass around, // seed dictionary ultimate returned // value. following lambda takes dictionary object (`dict`) // , current room ('current') add dictionary.  names.aggregate (new dictionary<int, list<string>>(), (dict, current) =>             {                current.userid.foreach(id => {                                                if (dict.containskey(id) == false)                                                   dict.add(id, new list<string>());                                                 dict[id].add(current.name);                                             });                 return dict;             }); 

result:

enter image description here


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -