Casting from System.Linq.EnumerableQuery to System.Data.Datatable (using Dynamic LINQ) - vb.net

I'm trying to get the results from a Dynamic LINQ query into a DataTable. Trying to get the query directly into a DataTable gives me this error:
Unable to cast object of type 'System.Linq.EnumerableQuery`1[DynamicClass1]' to type 'System.Data.DataTable'.
My code is:
Dim query = tbl.AsEnumerable.AsQueryable.Select("new(it[""curr""] as Curry)")
Dim tbl As DataTable = query
Ive tried:
Dim query As IEnumerable(Of DataRow) = tbl.AsEnumerable.AsQueryable.Select("new(it[""curr""] as Curry)").Cast(Of DataRow)()
Dim tbl1 As DataTable = query.CopyToDataTable
but that gives me:
Unable to cast object of type 'DynamicClass1' to type 'System.Data.DataRow'.

Public Shared Function ConvertIEnumerableToDataTableFromProperties(Of T)(ByVal list As IEnumerable(Of T)) As DataTable
Dim table As New DataTable()
Dim fields() As PropertyInfo = GetType(T).GetProperties()
For Each field As PropertyInfo In fields
table.Columns.Add(field.Name, field.PropertyType)
Next
For Each item As T In list
Dim row As DataRow = table.NewRow()
For Each field As PropertyInfo In fields
row(field.Name) = field.GetValue(item)
Next
table.Rows.Add(row)
Next
Return table
End Function

Related

Value of type 'String' cannot be converted to 'String()'

I am trying to add a value from DataTable dtUsers into a list UserLocations however I am getting the title error.
My code is:
Public UserLocations As New List(Of String())
For Each NewRow As DataRow In dtUsers.Rows
Dim seq As String = NewRow("SEQUENCE").Value.ToString
If CandRow("SQ") = NewRow("SQ") Then
UserLocations.Add(seq)
End If
Next
I don not understand why I cannot add a string to a list of strings.
How should I go about this?
Public UserLocations As New List(Of String)
For Each NewRow As DataRow In dtUsers.Rows
Dim seq As String = NewRow("SEQUENCE").Value.ToString()
If CandRow("SQ") = NewRow("SQ") Then
UserLocations.Add(seq)
End If
Next

Type casting anonymous type to IEnumerable type

Code:
Dim query As IEnumerable(Of DataRow) = From row In datatable.AsEnumerable() _
Select New With {
.messageId = row.Field(Of Integer)("Message_Id"), _
.severity = row.Field(Of String)("Severity")}
Dim dt As DataTable = query.CopyToDataTable
I am taking a few columns from a DataTable and copying into a new DataTable. But it gives me the following error:
System.Data.EnumerableRowcollection (of anonymous type) cannot be
converted System.collections.Generic.IEnumerable (of
System.data.datarow).
How do I proceed?
You are creating a new type here:
Select New With {
.messageId = row.Field(Of Integer)("Message_Id"),
.severity = row.Field(Of String)("Severity")
}
And trying to cast that new type into a DataRow. That's why you are getting the error.
You can you use the following code to filter your data:
Dim query = From row As DataRow In dtTable.Rows
Where row("colunm_name").ToString = "condition"
Select row
This will give you IEnumerable(Of DataRow).

return Datatable from linq query

I am trying to return data table from linq query but getting error message. I am using .net framework 4.0 in VS2012.
<Table>
Public Class StaffOfficeAccess
<Column(CanBeNull:=False, IsPrimaryKey:=True, IsDbGenerated:=True)>
Public Property StaffOfficeAccessID As Int32 = 0
<Column>
Public Property StaffID As Int32 = 0
<Column>
Public Property OfficeID As Int32 = 0
<Column(IsVersion:=True, IsDbGenerated:=True)>
Public Property Version As Byte()
End Class
'----------------------------'
Public Function GetByStaffID(ByVal staffID As Int32) As DataTable
Dim query As IEnumerable(Of DataRow) = CType((From oa In db.StaffOfficeAccess.AsEnumerable() _
Join o In db.Office.AsEnumerable() On oa.OfficeID Equals o.OfficeID _
Select oa.OfficeID,
o.OfficeName), Global.System.Collections.Generic.IEnumerable(Of Global.System.Data.DataRow))
Dim table As DataTable = System.Data.DataTableExtensions.CopyToDataTable(query)
Return table
End Function
'-------error----------'
Unable to cast object of type 'd__614[staff.Objects.StaffOfficeAccess,AMIS.Objects.Office,System.Int32,VB$AnonymousType_02[System.Int32,System.String]]' to type 'System.Collections.Generic.IEnumerable`1[System.Data.DataRow]'.
I have tried the example here https://msdn.microsoft.com/en-us/library/bb396189%28v=vs.110%29.aspx but no luck. I don't get CopyToDataTable in VS2012.
Just another approach by using Aggregate extension method MSDN
Dim dt As New DataTable()
dt.Columns.Add("OfficeID", GetType(Integer))
dt.Columns.Add("OfficeName", GetType(String))
Dim query = From oa In db.StaffOfficeAccess.AsEnumerable()
Join o In db.Office.AsEnumerable()
On oa.OfficeID Equals o.OfficeID
Select oa.OfficeID, o.OfficeName
query.Aggregate(Of DataTable)(dt,
Function(dtb, o)
Dim dr As DataRow = dtb.NewRow()
dr.SetField("OfficeID", o.OfficeID)
dr.SetField("OfficeName", o.OfficeName)
dtb.Rows.Add(dr)
Return dtb
End Function)
I have tried this and it works.
Dim dt As New DataTable()
dt.Columns.Add("OfficeID", GetType(Integer))
dt.Columns.Add("OfficeName", GetType(String))
Dim query = From oa In db.StaffOfficeAccess.AsEnumerable() _
Join o In db.Office.AsEnumerable() On oa.OfficeID Equals o.OfficeID _
Select oa.OfficeID,
o.OfficeName
For Each item In query
Dim dr As DataRow = dt.NewRow()
dr("OfficeID") = item.OfficeID
dr("OfficeName") = item.OfficeName
dt.Rows.Add(dr)
Next

implicit conversion from object to boolean

I keep getting this exception "implicit conversion from object to boolean" for below expression how do i get rid of it?
Dim objRows As IEnumerable(Of DataRow) = (From myRow As DataRow In objDS.Tables(0).AsEnumerable Where myRow.Item(PERSON_ID_LIST) = personid).Cast(of DataRow)
Try
Dim objRows As IEnumerable(Of DataRow) =
From myRow As DataRow In objDS.Tables(0).AsEnumerable()
Where myRow.Field(Of Int32)("PERSON_ID_LIST") = personid
otherwise you have to tell us what PERSON_ID_LIST is.

Datatable.Select with Like in VB.net

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 AsEnumerable which returns an IEnumerable collection of DataRow. So we can apply the AsEnumerable function on a DataTable and then play with some LINQ on the resulting collection.
var items=(from p in myDataTable.AsEnumerable()
select new { ID= p.Field<int>("ID").
Name=p.Field<string>("Name")
}).ToList();
var filtered=items.Where(x => x.Name.Contains("Mike"));
EDIT : Here is the VB.NET Version ( Disclaimer: I am not a VB.NET guy. but i could build this code without any error)
Dim items = (From p In myDataTable.AsEnumerable()
Select New With {.ID = p.Field(Of Integer)("ID"),
.Name = p.Field(Of String)("Name")}).ToList()
Dim filtered = items.Where(Function(x) x.Name.Contains("Mike")).ToList()
VB
Private Function likes(ByVal dt As DataTable, ByVal column As String, ByVal value As String)
Dim result = dt.Clone()
For Each row As DataRow In From row1 As DataRow In dt.Rows Where (row1(column).Contains(value))
result.ImportRow(row)
Next
Return result
End Function
C#
private DataTable likes(ref DataTable dt, string column, string value)
{
DataTable result = dt.Clone();
foreach (DataRow row in from row1 in dt.Rowswhere (row1(column).Contains(value))) {
result.ImportRow(row);
}
return result;
}