未知数量清单的C相交#.NET [英] intersection of unknown number of lists c# .net
本文介绍了未知数量清单的C相交#.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典< 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;())。
获取路口
这篇关于未知数量清单的C相交#.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文