查找两个 .NET DataTable 的交集 [英] Finding the intersection of two .NET DataTables

查看:22
本文介绍了查找两个 .NET DataTable 的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .NET 中是否有一种相对简单的方法来获取两个 DataTable 的交集?

Is there a relatively straightforward way to get the intersection of two DataTables in .NET?

我可以想到明显的方法(我自己在 O(n^2) 中遍历两个表),但是如果可以的话,我想要更优雅的东西.我怀疑可能有一种我没有看到的智能方式.可读性和可维护性当然很重要,所以我尽量避免任何过于华而不实"的东西.

I can think of the obvious ways (iterating over both tables myself in O(n^2)), but I'd like something a little more elegant if it's available. I suspect there may be an intelligent way that I'm not seeing. Readability and maintainability are important, of course, so I'm trying to stay away from anything too "slick".

有什么好主意吗?

看起来 Bryan Watts 有一个非常棒的 3.5 解决方案,但不幸的是我使用的是 .NET 2.0(我应该提到.)

推荐答案

使用 .NET 3.5:

With .NET 3.5:

using System.Data;

public static class DataTableExtensions
{
    public static IEnumerable<DataRow> Intersect(this DataTable table, DataTable other)
    {
        return table.AsEnumerable().Intersect(other.AsEnumerable());
    }

    public static IEnumerable<DataRow> Intersect(this DataTable table, DataTable other, IEqualityComparer<DataRow> comparer)
    {
        return table.AsEnumerable().Intersect(other.AsEnumerable(), comparer);
    }
}

这篇关于查找两个 .NET DataTable 的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆