I have a dictionary<int, List<string>>
and I want to intersect all of the lists for each int.
How would I achieve that? I feel like this should be easy, but for some reason it's not working out.
Thanks.
I have a dictionary<int, List<string>>
and I want to intersect all of the lists for each int.
How would I achieve that? I feel like this should be easy, but for some reason it's not working out.
Thanks.
It's easy enough to iterate the sequence of lists, putting the first into a HashSet
and then intersecting each subsequence list with it:
public static IEnumerable<T> intersectAll<T>(IEnumerable<IEnumerable<T>> source)
{
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
return Enumerable.Empty<T>();
var set = new HashSet<T>(iterator.Current);
while (iterator.MoveNext())
set.IntersectWith(iterator.Current);
return set;
}
}
Using this you can write IntersectAll(dictionary.Values.Cast<IEnumerable<string>>())
to get the intersection.
I think you're looking for something like the following;
List<string> TheIntersection = myDict.Select(x => x.Value).Aggregate((c, n) => c.Intersect(n)).ToList();
I had a similar question as the OP a while back and ended up using Skeet's solution (which is similar to Servy's solution)
public List<T> IntersectAll<T>(IEnumerable<IEnumerable<T>> lists)
{
HashSet<T> hashSet = null;
foreach (var list in lists)
{
if (hashSet == null)
hashSet = new HashSet<T>(list);
else
hashSet.IntersectWith(list);
}
return hashSet == null ? new List<T>() : hashSet.ToList();
}
Then you can get your intersected list by ...
var intersectedList = IntersectAll(myDictionary.Values);