1

I have a DataTable filled with database table (two columns) id and class. I want to compare the column class value with string and find the corresponding id value. The classID should be int type.

My code:

    int classID = from DataRow row in dtClassesDb.Rows where
                  row.ItemArray[1].ToString().Equals(table.TableName) 
                  select row.ItemArray[0];
  • If you are interested at efficient queries, you could consider creating an index in the `DataTable`, by creating a `DataView`. Take a look at [this](https://stackoverflow.com/questions/1109550/do-ado-net-datatables-have-indexes) question. – Theodor Zoulias Aug 15 '20 at 20:18
  • I have read the link question. But in my case how would i do it? – Muhammad Rizwan Aug 16 '20 at 09:46

1 Answers1

1

Find the Id from a DataTble by comparing column class value with any given string.

int classID = (int) dtClassesDb.AsEnumerable().
                FirstOrDefault(x => x.Field<string>(1) == "YourStringToCompare").
                ItemArray[0];

Here:

  • Field<string>(1) is using column class index which is 1
  • ItemArray[0] is using column Id index which is 0

This is supposed to solve the query to get the Id.

Sh.Imran
  • 1,035
  • 7
  • 13