Get row index in a datatable for a particular column value

  1. What would be the syntax to get the row index if I have a particular “column_name” and a particular value for that “column_name”??
  2. What would be the syntax to assign a value to some other “column_name_2” in that particular identified row??

@Ayush_Raj

Both to be used in assign

  1. intRow = dt.Rows.IndexOf(dt.AsEnumerable.Where(function(x) x("ColumnName").ToString.Equals("ValueToBesearched"))(0))
  2. dt.Rows(int_Row)("ColumnName2") = "VALUE To be assigned"

cheers

2 Likes

Thank you , this is helpful
I have one more query :–
How can I use 2 column_name and their respective 2 values to get that particular row index ??

YourDataTableVar.AsEnumerable.ToList.FindIndex(Function (x) x("Column1").toString.Trim.Equals("YourValue") AndAlso (Function (x) x("Column2").toString.Trim.Equals("YourValue") )
1 Like

In Addition to above, there is also a good option to use the Query Syntax

(From i in Enumerable.Range(0, YourDataTableVar.Rows.Count)
Let d = YourDataTableVar.Rows(i)
Where d("Column1").toString.Trim.ToUpper.Equals("YourValue".toUpper)
Where d("Column2").toString.Trim.ToUpper.Equals("YourValue".toUpper)
Select x = i).DefaultIfEmpty(-1).First()

so we can more readable focus on the filter checks and will also return -1 in case of no row is found

1 Like

@Ayush_Raj

Yes you can in the above you can add any number of filters inside the where condition as needed

intRow = dt.Rows.IndexOf(dt.AsEnumerable.Where(function(x) x("ColumnName").ToString.Equals("ValueToBesearched") AndAlso x("ColumnName2").ToString.Equals("ValueToBesearched2"))(0))

cheers

1 Like

we keep in mind the following:

When an empty filterresult is the outcome the access of the first element with (0) will throw an exception. Thats why we are formulating more defensive statements e.g. as above with the DefaultIfEmpty approach

1 Like

@Ayush_Raj

As Defense you can first check if you are getting any values

dt.AsEnumerable.Where(function(x) x("ColumnName").ToString.Equals("ValueToBesearched") AndAlso x("ColumnName2").ToString.Equals("ValueToBesearched2")).Count>0

@ppr thanks for pointing

cheers

1 Like

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