开发者

compare two datasets and place values in a new dataset

开发者 https://www.devze.com 2023-02-02 12:41 出处:网络
I m working on ASP.NET using C#, i need to compare the data from two DataSets with a \"ID\" which is in both the开发者_高级运维 DataSets and then add all the matching rows to a New dataset. Setup a D

I m working on ASP.NET using C#, i need to compare the data from two DataSets with a "ID" which is in both the开发者_高级运维 DataSets and then add all the matching rows to a New dataset.


Setup a DataRelation between the the tables in each DataSet, then use the GetChildRows method to find the matches which you could then add to your new DataSet or any other data structure. See Introduction to DataRelation Objects for some examples.


This can be done by intersection of two datatables

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);
    }
}

This is a shameless port of an elegant solution :)

Suppose you have two datasets set1 and set2 which you wanna compare. Do this

var newtable = set1.Tables[0].Intersect(set2.Tables[0]).CopyToDataTable();

Post more details, if this is not what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号