简体   繁体   中英

Linq to check if the datarow exists in a datatable

I have my query as below

  DataRow dr = objDtModifier.Rows[num];
  var existingRows = resultDataTable.AsEnumerable().Where(row => row == dr);

But existingRows.Count always returns me zero .

Can anyone tell what's wrong here .

You are comparing a row object from the objDtModifier source colloction with a different set of row objects in a resultDataTable collection which will alway return an empty result set as they are a different set of object references (this is regardless of whether they contain the same data or not).
Is there a property you can test against? eg:

var existingRows = resultDataTable.AsEnumerable().Where(row => row.Id == dr.Id);

You compare a row object which you get from a table called objDtModifier against a row from a table called resultDataTable . So unless that's a typo this is probably what's wrong.

Edit : Even if they contain rows from the same database table you are comparing the object references of two different row objects - this will fail. You need to compare two columns which uniquely identify the row (or maybe a set of columns).

发生这种情况是因为row和dr不是同一对象,而您将要比较两个对象,请尝试检查row的列,例如主键值

No matter if they are same type. If objDtModifier and resultDataTable does not contain same instances the behaviour you get is correct.

row==dr uses equality by reference, like chris stated. if objDtModifier and resultDataTable contains diffrent row instances but refers to same data, you might want to use row.id==dr.id if id is the primary key of the datable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM