簡體   English   中英

將datatable轉換為IEnumerable <T> 傳遞給結果 <T> (IEnumerable的 <T> 數據);

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

我有一個名為Result<T>的對象,它有一個接受IEnumerable<T>參數的構造函數。 如果可能的話,我希望能夠傳入數據表。

我嘗試過datatable.AsEnumerable() ,但在我綁定數據時,它抱怨“MyProperty”不是'DataRow'類型的字段或屬性 - 這是有道理的,因為'MyProperty'不是'DataRow'的屬性,但它是我的數據表中的一列。

有沒有辦法將數據表轉換為可以傳遞給Result對象的東西,並且仍然將它綁定到gridview?

如果您可以編寫一個可以使用單個DataRow構造具有“MyProperty”的對象實例的函數,那么您可以這樣做:

datatable.AsEnumerable().Select(MyConversionFunction);

我最終使用Linq將數據表轉換為匿名對象數組。

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

然后我創建了一個泛型函數來使用類型推斷來將匿名對象數組放入Result對象的構造函數中

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

使用Dim result = GetResult(objs)調用

如果要將鍵入的數據表轉換為EnumerableRowCollection,可以使用以下命令:

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

怎么樣

table.Rows.Cast<DataRow>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM