2016-11-07 15 views
2

私はDictionary<Guid,IList<string>>を持っています。これはエンティティが持つことができるすべての名前を示しています。Dictionary <Guid、IList <String>>を辞書に入れる<string、IList <Guid>> LINQを使用していますか?

これを変換して、すべてのエンティティにマップされているすべての名前を確認します。 ので:

[["FFF" => "a", "b"], 
["EEE" => "a", "c"]] 

[["a" => "FFF", "EEE"], 
["b" => "FFF"], 
["c" => "EEE"]] 

になり、私はこれがforeachesで行うのは簡単です知っているが、LINQ/ToDictionaryと方法がある場合、私は思ったんだけど?

答えて

5
private static void Main(string[] args) 
{ 
    var source = new Dictionary<Guid, IList<string>> 
    { 
     { Guid.NewGuid(), new List<string> { "a", "b" } }, 
     { Guid.NewGuid(), new List<string> { "b", "c" } }, 
    }; 

    var result = source 
     .SelectMany(x => x.Value, (x, y) => new { Key = y, Value = x.Key }) 
     .GroupBy(x => x.Key) 
     .ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList()); 

    foreach (var item in result) 
    { 
     Console.WriteLine($"Key: {item.Key}, Values: {string.Join(", ", item.Value)}"); 
    } 
} 
2
var dic = new Dictionary<string, List<string>>() 
{ 
    {"FFF", new List<string>(){"a", "b"}}, 
    {"EEE", new List<string>(){"a", "c"}} 
}; 

var res = dic.SelectMany(x => x.Value, (x,y) => new{Key = y, Value = x.Key}) 
      .ToLookup(x => x.Key, x => x.Value); 
0
Dictionary<int,IList<string>> d = new Dictionary<int ,IList<string>>(){ 
{1,new string[]{"a","b"}}, 
{2,new string[]{"a","d"}}, 
{3,new string[]{"b","c"}}, 
{4,new string[]{"x","y"}}}; 

d.SelectMany(kvp => kvp.Value.Select(element => new { kvp.Key, element})) 
.GroupBy(g => g.element, g => g.Key) 
.ToDictionary(g => g.Key, g => g.ToList()); 
関連する問題