c# - 未知数量列表的交集 c# .net

标签 c# .net linq

我有一个 dictionary<int, List<string>>我想为每个 int 与所有列表相交。

我将如何实现?我觉得这应该很容易,但由于某种原因,它没有成功。

谢谢。

最佳答案

迭代列表序列很容易,将第一个放入 HashSet 中然后将每个子序列列表与它相交:

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<IEnumerable<string>>())得到路口。

关于c# - 未知数量列表的交集 c# .net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19984812/

相关文章:

C# - 关闭 - 澄清

c# - RabbitMQ 异步支持

.net - 如何为我的 .NET MVC 项目(在 Azure 存储模拟器上)创建新的 CloudBlobContainer 实例?

c# - 仅当字符串前面没有某些字符时,如何匹配它的一部分?

C# linq order by 和 take

C# - 如何将 For 循环转换为 Linq 表达式?

c# - 一系列xy坐标中的最短距离

c# - 是否有一种流畅的 NHibernate 方法可以索引所有外键而无需编码?

c# - 确定用户是否在 .NET 4.0 应用程序的 AD 组中

c# - LINQ to Entities 无法识别方法 'System.Collections.Generic.Dictionary`