Filter few columns with LINQ

lets have a look on the task

Mapped to your sample data we can summarize the Requirement:

  • filter all rows where value “Not-Found” is present in one or more datacolumn values

As mentioned already by others when working with Filter Datatable or close to your statement statement style it is a OR conjuction needed.

When we want to do it with a LINQ we can reduce redundant code parts and also make it more robust like (assumptions: simple datacolumn datatypes, no empty filter result expected)

(From d in dtData.AsEnumerable
Where d.ItemArray.Any(Function (x) x.ToString.ToUpper.Trim.Equals("NOT-FOUND")
Select r = d).CopyToDataTable

when a dedicated mentioning of the filter col names is preferred we can do:

(From d in dtData.AsEnumerable
Let cols = new String(){"Supplier.Name","Supplier.smVendorID","AgreementDate", "ExpirationDate"}
Where cols.Any(Function (c) d(c).ToString.ToUpper.Trim.Equals("NOT-FOUND")
Select r = d).CopyToDataTable

or with index

(From d in dtData.AsEnumerable
Where {0,1,2,3}.Any(Function (c) d(c).ToString.ToUpper.Trim.Equals("NOT-FOUND")
Select r = d).CopyToDataTable

But as show cased the redundant parts of trimming / toUpper… are avoided. Shifting to a contains check is also possible.

When empty results are to expect we do handle:
🚑 🆘 [FirstAid] Handling of The source contains no DataRows exception

About Filter approach options
About the options of filter a datatable Filter DataTable, Select, LINQ (there is also another variation available) the Blog was shared with you.

We would prefer to avoid the different discussions where we often do see missinterpretated facts used for argumentations or ignored facts isolated in too close scoped viewpoints.

Based on facts and clear on approach rating criteria sets we can define a rule:
Whenever the left side column value is to prepare/modify/convert… for the filtering THEN using filter datatable has a risk of not being the preferred approach.

As we feel that making the Bot more robust when trimming and toUpper case transforming the column value we do hit this rule

1 Like