如何使用lambda表达式来过滤数据行? [英] How do I use lambda expressions to filter DataRows?
问题描述
我怎么可以搜索排在数据表与一列COL1 =myvalue的
How can I search rows in a datatable for a row with Col1="MyValue"
我想是这样
Assert.IsTrue(dataSet.Tables[0].Rows.
FindAll(x => x.Col1 == "MyValue" ).Count == 1);
不过,当然还是不行!
But of course that doesn't work!
推荐答案
您可以使用 LINQ到数据集来做到这一点:
You can use LINQ to DataSets to do this:
Assert.IsTrue(dataSet.Tables[0].AsEnumerable().Where(
r => ((string) r["Col1"]) == "MyValue").Count() == 1);
请注意,你也可以做到这一点,而不调用断言:
Note, you can also do this without the call to Assert:
dataSet.Tables[0].AsEnumerable().Where(
r => ((string) r["Col1"]) == "MyValue").Single();
如果行数不等于一(因此,调用单次),则一个会抛出异常,而未处理的异常的应的失败,你的测试用例。就个人而言,我喜欢后者,因为它有一个更清晰的语义
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:
dataSet.Tables[0].AsEnumerable().Single(
r => ((string) r["Col1"]) == "MyValue");
此外,你可以充分利用的 字段
方法上的的http:// MSDN .microsoft.com / EN-US /库/ bb348900.aspx> DataRowExtensions
类以简化字段类型安全的访问(以及提供转换的额外的好处 的DBNull
在.NET空同行):
Additionally, you can take advantage of the Field
method on the DataRowExtensions
class to simplify type-safe access to the field (as well as providing the extra benefit of converting DBNull
to null counterparts in .NET):
dataSet.Tables[0].AsEnumerable().Single(
r => r.Field<string>("Col1") == "MyValue");
这篇关于如何使用lambda表达式来过滤数据行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!