I have a datatable where i am trying to do
datatable.Select(Name Like ‘#%#’) but getting error that invalid pattern(expecting result of a table with name col having #Mike#,#Brow#..). Using escape sequense dint for all items dint work fine too. Many suggest to use Linq – but am new to it. How can i do this filter with Linq from this datatable.
This is a sample of what i was trying to do..
Dim dtSamp As Data.DataTable
dtSamp = New Data.DataTable
dtSamp.Columns.Add("Name")
dtSamp.Columns.Add("Marks")
Dim dr As DataRow
dr = dtSamp.NewRow()
dr.Item(0) = "AAA"
dr.Item(1) = "50"
dtSamp.Rows.Add(dr)
dr = dtSamp.NewRow()
dr.Item(0) = "#bbb#"
dr.Item(1) = "60"
dtSamp.Rows.Add(dr)
dr = dtSamp.NewRow()
dr.Item(0) = "ccc"
dr.Item(1) = "44"
dtSamp.Rows.Add(dr)
Dim drResult As DataRow()
drResult = dtSamp.Select("Name Like '#%#'")
Dim dtOutPutTable As Data.DataTable
dtOutPutTable = drResult.CopyToDataTable()
In the dtOutPutTable i was expecting 1 row ie, #bbb# in it.. but the Select function fails.
Generally LINQ queries works on data sources which implement the
IEnumerable<T>/ IQueryable<T> Interface. But DataTable does not implement any of these. So we can not directly apply LINQ queries on a DataTable.But DataTable class has an extension method called
AsEnumerablewhich returns anIEnumerablecollection of DataRow. So we can apply theAsEnumerablefunction on a DataTable and then play with some LINQ on the resulting collection.EDIT : Here is the VB.NET Version ( Disclaimer: I am not a VB.NET guy. but i could build this code without any error)