C# Linq反转父子序列

C# Linq反转父子序列,c#,linq,C#,Linq,我有一系列这样的物体 A1 - B1, B2, B3 A2 - B1 A3 - B1, B2 (A是父对象,包含B个子对象的集合) 我想将其反转,以便子对象(B)成为父对象,即 B1 - A1, A2, A3 B2 - A1, A3 B3 - A1 有人知道正确的linq查询以获得此结果吗?首先,您可以在没有linq的情况下用自己的双手轻松完成此操作: //init original dictionary var dict = new Dictionary<string, List&l

我有一系列这样的物体

A1 - B1, B2, B3
A2 - B1
A3 - B1, B2
(A是父对象,包含B个子对象的集合)

我想将其反转,以便子对象(B)成为父对象,即

B1 - A1, A2, A3
B2 - A1, A3
B3 - A1

有人知道正确的linq查询以获得此结果吗?

首先,您可以在没有linq的情况下用自己的双手轻松完成此操作:

//init original dictionary
var dict = new Dictionary<string, List<string>>
{
    {"A1",new List<string> { "B1", "B2", "B3" }},
    {"A2",new List<string> { "B1" }},
    {"A3",new List<string> { "B1", "B2"}},
};
//do the task
var newdict = new Dictionary<string, List<string>>();
foreach (var p in dict)
{
    foreach (string s in p.Value)
    {
        if (!newdict.ContainsKey(s))
            newdict[s] = new List<string>();
        newdict[s].Add(p.Key);
    }
}
//see what we've got
foreach (var p in newdict)
{
    Console.WriteLine(p.Key);
    foreach (string s in p.Value)
    {
        Console.Write(s + "\t");
    }
    Console.WriteLine();
}
Console.ReadLine();
我在哪里

  • 使用
    SelectMany
    获取匿名对象的序列,表示密钥对和原始值列表中的每个值

  • 使用
    GroupBy
    实际反转列表并获得按值分组而不是按键分组的对序列

  • 使用
    ToDictionary
    创建与原始词典相同的结构,即
    Dictionary

附言:

有人知道获得此结果的正确linq查询吗

我想没人知道,但很多人都能弥补——这是你首先要做的,那就是努力

有人知道获得此结果的正确linq查询吗

LINQ相当直截了当,并紧跟@Konstantin的答案

var dict = new Dictionary<string, List<string>>
{
    {"A1",new List<string> { "B1", "B2", "B3" }},
    {"A2",new List<string> { "B1" }},
    {"A3",new List<string> { "B1", "B2"}},
};

IEnumerable<IGrouping<string,string>> inverted =
    from kvp in dict
    from child in kvp.Value
    group kvp.Key by child;

好的,我应该把我有的东西贴出来,但是没有用。我缺少的部分是SelectMany中的.Select。谢谢。@user380689请阅读Jon Skeet的文章。这篇文章确实指出了在这样的网站上写问题时需要记住的所有事情。遵循所有这些建议可能有助于避免将来的误解。我很高兴我的回答对你有帮助。当问题域需要一个多值字典时,你可以考虑使用TooCoCUP而不是To字典。@ EricLippert,我不确定,如果目标数据序列是容易修改的。因此,只要
ILookup
没有提供任何修改方法,我就决定使用更通用的
词典。嗯,我应该在回答中提到这一点。非常感谢。
var dict = new Dictionary<string, List<string>>
{
    {"A1",new List<string> { "B1", "B2", "B3" }},
    {"A2",new List<string> { "B1" }},
    {"A3",new List<string> { "B1", "B2"}},
};

IEnumerable<IGrouping<string,string>> inverted =
    from kvp in dict
    from child in kvp.Value
    group kvp.Key by child;
Dictionary<string,List<string>> invertedDict = 
    inverted.ToDictionary(i => i.Key, i => i.ToList());