如何使用lambda表达式过滤DataRows? [英] How do I use lambda expressions to filter DataRows?

查看:273
本文介绍了如何使用lambda表达式过滤DataRows?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Col1 =MyValue搜索行的数据表中的行?

我正在考虑像

  Assert.IsTrue(dataSet.Tables [0] .Rows。
FindAll(x => x.Col1 ==MyValue).Count = = 1);

但当然不行!

解决方案

您可以使用 LINQ to DataSet 这样做:

  Assert.IsTrue(dataSet.Tables [0] .AsEnumerable()。Where(
r =>((string)r [Col1])==MyValue)。Count()== 1);

请注意,您也可以不用调用Assert:

  dataSet.Tables [0] .AsEnumerable()。其中​​(
r =>((string)r [Col1])== MyValue)。Single();

如果行数不等于1(因此调用Single),那么将抛出异常,并且未处理的异常应该失败您的测试用例。个人来说,我喜欢后者,因为它具有更清晰的语义含义。



以上可以进一步削减到:



$ pre> dataSet.Tables [0] .AsEnumerable()。Single(
r =>((string)r [Col1])==MyValue ;

此外,您可以利用 Field 方法 DataRowExtensions class 以简化安全性访问该字段(以及提供转换 <$ c的额外好处$ c> DBNull 在.NET中对齐):

  dataSet.Tables [0] .AsEnumerable()。Single(
r => r.Field< string>(Col1)==MyValue);


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:

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");

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表达式过滤DataRows?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆