Reverse many-to-many Dictionary>

前端 未结 3 1920
再見小時候
再見小時候 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:55

    To reverse a dictionary is very easy:

    var newDic = oldDic.ToDictionary(x => x.Value, x => x.Key);
    

    That's all.

    Now, your question is different. It is about reversing a many-to-many relationship, established on a dictionary.

    So, let's say you have Dictionary>. The idea is to extract from this the "middle table" of the many-to-many relationship. Then you can regroup it by the other side, and retransform into a dictionary.

    For the first part, we will use the overload of SelectMany that

    "Projects each element of a sequence to an IEnumerable, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein."

    var table =
        dict.SelectMany(
            x => x.Value,
            (dictEntry, entryElement) => new
                   {
                          Entity1 = dictEntry.Key,
                          Entity2 = entryElement
                   }
        );
    

    So, now you just have to regroup this table the way you want, and then convert it to a dictionary.

     var newDict =
         table
             .GroupBy(x => x.Entity2,
                      x => x.Entity1,
                      (entity2, entity1) => new {entity1, entity2})
             .ToDictionary(x => x.entity2, x => x.entity1);
    

提交回复
热议问题