使用Linq从动态字段中获取价值

时间:2015-01-06 10:30:09

标签: vb.net linq dynamic

我有一个对象列表。我想在动态字段中获取所有值。 我解释得更多。我读了动态对象的所有属性。当我找到一个图像字段时,我想获取对象列表中的所有图像。

  For Each col In Ret.StructTbl.LstCol
      If col.EstImage Then
          col.Liste = GetType(List(Of Eleve)).GetProperty(col.SQLName).GetValue(Ret.LstDatas.LstObj, Nothing) 
      End If
  Next

我用它(vb.net),但我

  

Laréférenced'objetn'estpasdéfinieàuneinstance d'un objet

我认为这是因为我有一些空值或者我采取了错误的方式? 它是filter and sorter dynamic null value

的后续内容

我的结构

Public Class Eleve

<TableFullOption.TFOAttribute("Key")> Property Id As Integer
<TableFullOption.TFOAttribute("Image")> Property Img As String
Property Name As String
Property Major As Boolean
<TableFullOption.TFOAttribute("FK_Sexe")> Property Sex As Integer
Property English As Nullable(Of Integer)
Property Japanese As Nullable(Of Double)
Property Calculus As Decimal
Property Geometry As Integer
End Class

和col.SQLName =“Img”

你能帮帮我吗? 我想列出我所有的图像(mypicture.jpg,img1.png ......)

2 个答案:

答案 0 :(得分:1)

GetProperty()语句返回Nothing,因为在List(T)类型上找不到属性名称。

GetType(List(Of Eleve)).GetProperty(col.SQLName) = Nothing ' true

在下一次调用GetValue()时会引发异常,因为您实际上是在空引用上调用方法。

Nothing.GetValue(...)

您是否打算在Eleve类型上找到属性?

GetType(Eleve).GetProperty(col.SQLName)

答案 1 :(得分:0)

我发现...... 首先,我创建一个智能功能

 Public Shared Function GetColumn(Of MaClass As Class)(ByVal items As List(Of MaClass), ByVal columnName As String) As List(Of String)
    Return items.Select(Function(x) If(x.GetType().GetProperty(columnName).GetValue(x, Nothing), String.Empty).ToString).ToList
End Function

我称之为

 For Each col In Ret.StructTbl.LstCol
     If col.EstImage Then
         col.Liste = GetColumn(Of Eleve)(Ret.LstDatas.LstObj, col.SQLName)
     End If
 Next