Reverse many-to-many Dictionary>

前端 未结 3 1888
再見小時候
再見小時候 2021-02-05 05:41

Actually my previous question got me thinking and I realized that reversing a Dictionary is not trivial. What is the most elegant and readable way to do it?

3条回答
  •  灰色年华
    2021-02-05 05:50

    Slightly different way (a bit more comprehensible to my brain anyway :) ...

    var newDict = new Dictionary>();
    var dict = new Dictionary>();
    dict.Add( 1, new List() { 1, 2, 3, 4, 5 } );
    dict.Add( 2, new List() { 1, 2, 3, 4, 5 } );
    dict.Add( 3, new List() { 1, 2, 6 } );
    dict.Add( 4, new List() { 1, 6, 7 } );
    dict.Add( 5, new List() { 8 } );
    
    var newKeys = dict.Values.SelectMany( v => v ).Distinct();
    
    foreach( var nk in newKeys )
    {
       var vals = dict.Keys.Where( k => dict[k].Contains(nk) );
       newDict.Add( nk, vals.ToList() );
    }
    

提交回复
热议问题