Mathematics
Mathematics

Reputation: 7628

Searching for a string a column in datatable

I am getting a datatable object of a certain type from strongly typed dataset, now I want to find out if one of the column "Title" has certain string in it.

I am trying this, is there any better way ?

   FruitDataAccess fda = new FruitDataAccess();
   FruitDataTable fdt = cda.GetFriuts(fruitCrateID);
   DataTable dt = fdt.CopyToDataTable();
   var row = dt.Rows.Cast<DataRow>().Any(r => r.ItemArray.Any(c => c.ToString().Contains("whatever"))); 

Upvotes: 0

Views: 83

Answers (1)

Habib
Habib

Reputation: 223432

Use LINQ TO DataSet/DataTable like:

var search = dt.AsEnumerable()
              .FirstOrDefault(r=> r.Field<string>("Title") == "your string");

if(search != null)
{
    //found
}

You can also find rows with your condition like:

DataRow[] foundRows;
foundRows = dt.Select("Title Like '%your string%'"); //similar to Contains

See: How to: Locate a Specific Row in a DataTable

Upvotes: 2

Related Questions