[英]How to compare two DataSet columns values in C#?
In below code i want to compare two dataset column's values but its not match then also getting true this condition.so how to really compare?在下面的代码中,我想比较两个数据集列的值但它不匹配然后也得到了这个条件。那么如何真正比较?
if (dsEmp.Tables[0].Columns["EmpName"].ToString() == dsAllTables.Tables[2].Columns["EmpName"].ToString())
{
}
You are comparing two column-names, so "EmpName"
with "EmpName"
which is always true. 您正在比较两个列名,因此"EmpName"
与"EmpName"
始终为真。 Tables[0].Columns["EmpName"]
returns a DataColumn
with that name and ToString
returns the name of the column which is "EmpName"
. Tables[0].Columns["EmpName"]
返回具有该名称的DataColumn
,而ToString
返回列的名称为"EmpName"
。 So that's pointless. 所以这毫无意义。
If you instead want to know if two tables contain the same EmpName
value in one of their rows you can use LINQ: 相反,如果您想知道两个表在它们的某一行中是否包含相同的EmpName
值,则可以使用LINQ:
var empRowsEmpName = dsEmp.Tables[0].AsEnumerable().Select(r => r.Field<string>("EmpName"));
var allRowsEmpName = dsAllTables.Tables[2].AsEnumerable().Select(r => r.Field<string>("EmpName"));
IEnumerable<string> allIntersectingEmpNames = empRowsEmpName.Intersect(allRowsEmpName);
if (allIntersectingEmpNames.Any())
{
}
Now you even know which EmpName
values are contained in both tables. 现在,您甚至知道两个表中都包含哪些EmpName
值。 You could use a foreach
-loop: 您可以使用foreach
-loop:
foreach(string empName in allIntersectingEmpNames)
Console.WriteLine(empName);
If you want to find out if a specific value is contained in both: 如果要查找两者中是否都包含特定值,请执行以下操作:
bool containsName = allIntersectingEmpNames.Contains("SampleName");
If you just want to get the first matching: 如果您只想获得第一个匹配项:
string firstIntersectingEmpName = allIntersectingEmpNames.FirstOrDefault();
if(firstIntersectingEmpName != null){
// yes, there was at least one EmpName that was in both tables
}
If you have a single row, this should work: 如果只有一行,这应该可以:
if (dsEmp.Tables[0].Row[0]["EmpName"].ToString() == dsAllTables.Tables[2].rows[0]["EmpName"].ToString())
{
}
For multiple rows you have to iterate through table: 对于多行,您必须遍历表:
for (int i = 0; i <= dsEmp.Tables[0].Rows.Count; i++)
{
for (int j = 0; j <= dsAllTables.Tables[0].Rows.Count; j++)
{
if (dsEmp.Tables[0].Rows[i]["EmpName"].ToString() == dsAllTables.Tables[2].Rows[j]["EmpName"].ToString())
{
}
}
}
I have two datatables - dtbl and mtbl, and I use this to return records that have a difference, as another DataTable.
我有两个数据表 - dtbl 和 mtbl,我用它来返回有差异的记录,作为另一个DataTable.
//compare the two datatables and output any differences into a new datatable, to return
var differences = dtbl.AsEnumerable().Except(mtbl.AsEnumerable(), DataRowComparer.Default);
return differences.Any() ? differences.CopyToDataTable() : new DataTable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.