Finding the intersection of two .NET DataTables

前端 未结 4 1522
野的像风
野的像风 2020-12-09 22:30

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

I can think of the obvious ways (iterating over both tables myself in O(

4条回答
  •  时光说笑
    2020-12-09 22:50

    Saw this example on MSDN which you may find useful. Its using the LINQ syntax.

    DataSet ds = new DataSet();
    ds.Locale = CultureInfo.InvariantCulture;
    FillDataSet(ds);
    
    DataTable orders = ds.Tables["SalesOrderHeader"];
    DataTable details = ds.Tables["SalesOrderDetail"];
    
    var query =
        from order in orders.AsEnumerable()
        join detail in details.AsEnumerable()
        on order.Field("SalesOrderID") equals
            detail.Field("SalesOrderID")
        where order.Field("OnlineOrderFlag") == true
        && order.Field("OrderDate").Month == 8
        select new
        {
            SalesOrderID =
                order.Field("SalesOrderID"),
            SalesOrderDetailID =
                detail.Field("SalesOrderDetailID"),
            OrderDate =
                order.Field("OrderDate"),
            ProductID =
                detail.Field("ProductID")
        };
    
    
    foreach (var order in query)
    {
        Console.WriteLine("{0}\t{1}\t{2:d}\t{3}",
            order.SalesOrderID,
            order.SalesOrderDetailID,
            order.OrderDate,
            order.ProductID);
    }
    

提交回复
热议问题