翻字典>Dictionary<字符串,IList< Guid>祝辞LINQ
本文关键字:IList Guid gt LINQ 祝辞 String 字典 Dictionary 字符串 | 更新日期: 2023-09-27 18:16:45
我有一个Dictionary<Guid,IList<string>>
,它显示了一个实体可以拥有的所有名称。
我想将其转换为查看映射到所有实体的所有名称。所以:
[["FFF" => "a", "b"],
["EEE" => "a", "c"]]
是
[["a" => "FFF", "EEE"],
["b" => "FFF"],
["c" => "EEE"]]
我知道这很容易做到与foreaches,但我想知道是否有一种方法与LINQ/ToDictionary?
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)}");
}
}
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);
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());