【问题标题】:How to compare two DataSet using HashSet in asp.net c#如何在asp.net c#中使用HashSet比较两个DataSet
【发布时间】:2012-09-13 09:06:35
【问题描述】:

我将两个表添加到数据集中,我想检查它们是否相等。

我试过的代码是:

SqlDataAdapter mydat = new SqlDataAdapter("Select Device_Profile_Param+'='+Device_Profile_Default_Value AS SettingsCheck From Device_Profile_Master Where Device_Profile_Name = '" + Label5.Text + "'", con); 
DataTable dt = new DataTable(); 
mydat.Fill(dt);

DataSet dset = new DataSet();
dset.Tables.Add(dt);

SqlDataAdapter mydata = new SqlDataAdapter("Select Device_Profile_Param+'='+Device_Profile_Default_Value AS Settings From Device_Profile_Master Where Device_Profile_Name = '" + For_Profile_Num.Items[i] + "'", con);
DataTable dt2 = new DataTable();
mydata.Fill(dt2);

dset.Tables.Add(dt2);

var hashSet1 = new HashSet<string>(dset.Tables[0].Rows.Cast<ListItem>().Select(x => x.Value));
var hashSet2 = new HashSet<string>(dset.Tables[1].Rows.Cast<ListItem>().Select(x => x.Value));

var result = hashSet1.SetEquals(hashSet2);
if (result == true)
{
found = 1;
}

我收到一个错误DataSet 无法转换为 ListItem。请帮忙。

【问题讨论】:

  • 是否有必要将行转换为 ListItem?可以这样写吗:dset.Tables[0].Rows.Select(x=&gt;x["ColumnName"].value)
  • 我试过它说DataSet Row没有任何Select方法。

标签: c# asp.net sql-server-2008


【解决方案1】:

在添加到 HashSet 时定义一些列名...

System.Collections.Hashtable myHashtable1 = new System.Collections.Hashtable();
                myHashtable.Add(dset.Tables[0].Rows[0]["Column1"], myDataTable1.Rows[0]["Column2"]);
                myHashtable.Add(dset.Tables[0].Rows[1]["Column1"], myDataTable1.Rows[1]["Column2"]);

System.Collections.Hashtable myHashtable2 = new System.Collections.Hashtable();
                myHashtable.Add(dset.Tables[1].Rows[0]["Column1"], myDataTable1.Rows[0]["Column2"]);
                myHashtable.Add(dset.Tables[1].Rows[1]["Column1"], myDataTable1.Rows[1]["Column2"]);


var result = myHashtable2 .SetEquals(myHashtable1);
if (result == true)
{
found = 1;
}

同样...

希望对你有帮助

【讨论】:

  • 在此之后如何比较..?
  • 这是将其添加到哈希表的方法,然后您可以使用 var result = hashSet1.SetEquals(hashSet2); 进行比较只有...我相信您在将 DataTable 添加到 HashTable 而不进行比较时遇到问题?
  • 是的,没错,但是在代码中你已经给出了如何将 datatable1 分别放入 hashSet1 和 datatable1 到 hashSet2。
【解决方案2】:

使用IEnumerable 作为Follow 来比较两个表...

IEnumerable<string> table1Value= dset.Tables[0].AsEnumerable().Select(x => (string)x[ColumnName]); 

IEnumerable<string> table2Value= dset.Tables[1].AsEnumerable().Select(x => (string)x[ColumnName]); 

IEnumerable<string> ChangedValue = table2Value.Except(table1Value); 

如果 ChangedValued 为 null 或为空,则两个表相同

【讨论】:

  • 不一样,有一种情况是table1Value包含table2Values的所有值,包括其他一些值。
  • 是的,我同意,那么我们将不得不在两种方式中都编写 except 并检查两个结果是否为空或 null
猜你喜欢
  • 2010-11-14
  • 1970-01-01
  • 2021-11-30
  • 2012-03-21
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多