How to get datarow from Datatable with two Columns Condition using LINQ

I am trying to get the first Data row where the Column Name is equal to variable name and Column age is equal to variable age, using linq.
Code that I have tried.

DT_Customer.AsEnumerable.where(Function(x)x("Name").ToString.Equals(Name)AND x("Age").ToString.Equals(Age)).FirstOrDefault

Hi @Shinjid

Please try this,

DT_Customer.AsEnumerable.where(Function(x) x(“Name”).ToString.Equals(Name)and x(“Age”).ToString.Equals(Age))(0)

Use index instead of getting first or default method because when there is no row matching with the condition instead of throwing a error it will try to give a default value.

If you are getting error then that means there is no row matching with the condition.

Thanks

@Shinjid

May I know what error are you getting ?

     matchingRow = DT_Customer.AsEnumerable.where(Function(x)x("Name").ToString.Equals(Name)AND x("Age").ToString.Equals(Age))(0)

Where matchingRow is of type System.Data.DataRow

Hi

You are almost done
With your expression

FirstOrDefault - this will return the exact row by looking the first column(Name) = Name.ToString and also the second condition
It will validate this input string with all the rows. If it matches then it will return the whole datarow.

So May I know what error you are getting
I think this should work already

Cheers @Shinjid

It says Column age does not belong to the datable, that is my 2nd column

Fine
Does datatable have that column Age
Or
Try with column index as 1 instead of column name “Age”
Can we check once @Shinjid

@Shinjid

Is column name Age or age in your input file ? Provide exact column name and it should be case sensitive.

OMG! I am sorry guys. I hate that I always get problems with silly reasons, this always happens. Turns out, my column ‘Age’ has an extra whitespace it the end. Is there a way to update it without looping?

Then mention like this “Age “

If you want to update column name
Then

dt.Columns(your columnindex).ColumnName = “new Name”

Cheers @Shinjid

@Shinjid

Is column header contains white space or its row values ?

Column header, I just added a space on the linq.

Thank you! I just noticed it right now. My clients documents always have this weird whitespaces in random places. Sorry for the troublle

1 Like

Glad it got resolved
@Shinjid

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.