开发者

Convert datatable to IEnumerable<T> to pass to Result<T>(IEnumerable<T> data);

I have an object called Result<T> that has a constructor which accepts an argument of IEnumerable<T>. I'd like to be able to pass in a datatable if possible.

I tried datatable.AsEnumerable(), but where I bind to the data it was complaining that 'MyProperty' is not a field or property on type 'DataRow' - which makes sense since 'MyProperty' isn't a property on 'DataRow', but it was a column in my datatable.

Is there a way to convert a datatable to something that I can pass into the Result object and still have it开发者_C百科 bind to, say, a gridview?


If you can write a function that can construct an instance of the object that has 'MyProperty' using a single DataRow, then you can do it like this:

datatable.AsEnumerable().Select(MyConversionFunction);


I ended up using Linq to convert the datatable into an array of anonymous objects.

Dim objs = From row In dt Select New With {
    .Id = row.Field(Of Integer)("Id"),
    .Count = row.Field(Of Integer)("Count")
}

Then I created a generic function to use type inference to get the anonymous object array into the Result object's constructor

Private Function GetResult(Of T)(ByVal data As IEnumerable(Of T)) As Result(Of T)
    Return New Result(Of T)(Nothing, data)
End Function

Called using Dim result = GetResult(objs)


How about

table.Rows.Cast<DataRow>()


If you want to convert your typed datatable to a EnumerableRowCollection you can use the following:

EnumerableRowCollection<YourTypedRow> typedRowCollection = datatable.AsEnumerable().Cast<YourTypedRow>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜