我有一个字典< INT,列表和LT;字符串>>
,我想相交所有列表的每个INT
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.
感谢。
这是很容易来循环列表的顺序,把第一次到的HashSet
,然后相互交叉子列表吧:
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;
}
}
使用这个你可以写 IntersectAll(dictionary.Values.Cast&LT; IEnumerable的&LT;字符串&GT;&GT;())。
获取路口