How can I search rows in a datatable for a row with Col1="MyValue"
I'm thinking something like
Assert.IsTrue(dataSet.Tables[0].Rows.
FindAll(x => x.Col1 == "MyValue" ).Count == 1);
But of course that doesn't work!
How can I search rows in a datatable for a row with Col1="MyValue"
I'm thinking something like
Assert.IsTrue(dataSet.Tables[0].Rows.
FindAll(x => x.Col1 == "MyValue" ).Count == 1);
But of course that doesn't work!
You can use LINQ to DataSets to do this:
Note, you can also do this without the call to Assert:
If the number of rows does not equal one (hence, the call to
Single
), then an exception will be thrown, and that unhandled exception should fail your test case. Personally, I like the latter, as it has a clearer semantic meaning.The above can be further whittled down to:
Additionally, you can take advantage of the
Field
method on theDataRowExtensions
class to simplify type-safe access to the field (as well as providing the extra benefit of convertingDBNull
to null counterparts in .NET):You can use the
Select
method of the data table to do this, or the Filter Property of theDefaultDataView
on the table.For the
Select
method:For the
DefaultView
Filter:Why use lambda and not select?
You can try this:
The code you wrote checks that there's only one row which fulfils your search condition. If you actually want the rows, drop the
Assert
andCount