C# 使用Linq通过唯一键创建列表

C# 使用Linq通过唯一键创建列表,c#,linq,C#,Linq,我有一个类型依赖的类: class Dependency { public int Source; public int Target: } 给定一个列表,我会有以下列表,每一行都是源/目标对: 1, 2 1, 5 2, 1 3, 4 3, 6 是否可以将它们与Linq合并,以便生成以下列表您可以像这样使用Linq group by运算符: var items = new List<Dependency>(); // add your items to list

我有一个类型依赖的类:

class Dependency
{
    public int Source;
    public int Target:
}
给定一个列表,我会有以下列表,每一行都是源/目标对:

1, 2
1, 5
2, 1
3, 4
3, 6

是否可以将它们与Linq合并,以便生成以下列表您可以像这样使用Linq group by运算符:

var items = new List<Dependency>();
// add your items to list

var result = (from i in items
             group i by i.Source
             into gr
             select new Tuple<int, List<int>>(gr.Key, gr.Select(a => a.Target).ToList())).ToList();
上面的查询应该相当快,尽管很难与其他实现相同功能的方法进行比较。我建议在实践中进行测试——编写替代实现并比较性能

注意:建议将C的组转换为语法。我的回答显示了类似的东西,即.ToLookup…操作符。如果您想了解这两个问题之间的区别,请参见以下问题:

下面的解决方案不会给出一个列表,我不能说它是否是最快的解决方案,但它很可能是最简洁的:

ILookup<int,int> multiMap = dependencies.ToLookup(d => d.Source, d => d.Target);

那么,源和目标是分开的列表,还是一个具有属性Source和Target的类呢?修改后的问题包括按源和其他类型的类应该很容易。但是,不能谈论速度。如果您希望使用等效的方法:items.GroupByx=>x.Source,k,x=>newtuplek,x.Selectg=>g.Target.ToList.ToList;
ILookup<int,int> multiMap = dependencies.ToLookup(d => d.Source, d => d.Target);
foreach (IGrouping<int,int> grouping in multiMap)  // enumerate over all groups
foreach (int target in grouping)  // enumerate over all values in one specific group
{
    int source = grouping.Key;  // get the key value of the group
    …
}