How do I use lambda expressions to filter DataRows?

后端 未结 5 710
天涯浪人
天涯浪人 2021-02-13 09:20

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 =&g         


        
5条回答
  •  后悔当初
    2021-02-13 09:42

    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("Col1") == "MyValue");
    

提交回复
热议问题