Note: This other answer recommends C#'s group into
syntax. My answer shows something similar, namely the .ToLookup(…)
operator. If you're asking what the difference between these two is, see e.g. the following question: ILookup<TKey, TVal> vs. IGrouping<TKey, TVal>.
The following solution won't yield a List<Tuple<int, List<int>>>
, and I cannot say whether it is the fastest solution, but it's quite probably the most succinct:
ILookup<int,int> multiMap = dependencies.ToLookup(d => d.Source, d => d.Target);
The .ToLookup(…)
operator groups your dependencies
by their Source
property (as specified by the first lambda), and instead of putting complete Dependency
objects into the output, it only selects their Target
values (as specified by the second, optional lambda).
What you get is an ILookup<TKey,TElement>
, which is essentially like a Dictionary<TKey,TValue>
, except that there can be several elements (values) per key.
Here's an example how you can iterate over all the values in such a data structure (a so-called multimap):
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
…
}