Kuntady Nithesh
Kuntady Nithesh

Reputation: 11731

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 .

Upvotes: 1

Views: 4520

Answers (4)

Andy Rose
Andy Rose

Reputation: 17014

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

Upvotes: 4

Cristian
Cristian

Reputation: 23

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.

Upvotes: 0

ChrisWue
ChrisWue

Reputation: 19070

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).

Upvotes: 1

DeveloperX
DeveloperX

Reputation: 4683

It happens because row and dr not same object and your are going to compare two object, try to check columns of row , something like primary keyvalue

Upvotes: 1

Related Questions