Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将datatable转换为IEnumerable<;T>;传递到结果<;T>;(IEnumerable<;T>;数据);_C#_Asp.net_Vb.net_Generics_Datatable - Fatal编程技术网

C# 将datatable转换为IEnumerable<;T>;传递到结果<;T>;(IEnumerable<;T>;数据);

C# 将datatable转换为IEnumerable<;T>;传递到结果<;T>;(IEnumerable<;T>;数据);,c#,asp.net,vb.net,generics,datatable,C#,Asp.net,Vb.net,Generics,Datatable,我有一个名为Result的对象,它有一个接受IEnumerable参数的构造函数。如果可能的话,我希望能够传入一个数据表 我尝试了datatable.AsEnumerable(),但当我绑定到数据时,它抱怨“MyProperty”不是类型“DataRow”上的字段或属性,这很有意义,因为“MyProperty”不是“DataRow”上的属性,而是我的datatable中的列 有没有一种方法可以将datatable转换为我可以传递到结果对象并仍然将其绑定到(比如)gridview的对象?如果您可以

我有一个名为
Result
的对象,它有一个接受
IEnumerable
参数的构造函数。如果可能的话,我希望能够传入一个数据表

我尝试了
datatable.AsEnumerable()
,但当我绑定到数据时,它抱怨“MyProperty”不是类型“DataRow”上的字段或属性,这很有意义,因为“MyProperty”不是“DataRow”上的属性,而是我的datatable中的列


有没有一种方法可以将datatable转换为我可以传递到结果对象并仍然将其绑定到(比如)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")
}
然后我创建了一个泛型函数,使用类型推断将匿名对象数组放入结果对象的构造函数中

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)调用

table.Rows.Cast<DataRow>()
table.Rows.Cast()

如果要将键入的数据表转换为EnumerablerRowCollection,可以使用以下方法:

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

为什么不直接使用实体框架呢?IIRC,它是dtatable.Rows.AsEnumerable()@Cylon Cat-Nope,它是。那会怎么样?你不会还会遇到同样的问题吗?”“MyProperty”不会是DataRow实例上的属性。好吧,这应该会给你行,你确实可以访问每行上的每一列,例如在for each循环中,这将是每行的
,作为DataRow in rows Dim val=row(“MyProperty”)Next