VB.NET使用LINQ来转置ObservableCollection

时间:2010-08-11 16:10:37

标签: wpf vb.net linq

我有一个自定义项类(基本上是两个带有相关属性的字符串值),如下所示:

Public Class itmDataDetails
    Private _strDataName As String
    Private _strDataValue As String

    Public Property strDataName() As String
        Get
            Return _strDataName
        End Get
        Set(ByVal value As String)
            _strDataName = value
        End Set
    End Property

    Public Property strDataValue() As String
        Get
            Return _strDataValue
        End Get
        Set(ByVal value As String)
            _strDataValue = value
        End Set
    End Property

    Public Sub New(Optional ByVal strDataNameIn As String = "", Optional ByVal strDataValueIn As String = "")
        strDataName = strDataNameIn
        strDataValue = strDataValueIn
    End Sub

和一个ObservableCollection包装类。我想将这个ObservableCollection转换(即将数据名称放入列及其关联值到行中),以便在WPF ListView中显示。

这是我到目前为止所拥有的:

Private Sub Transpose()
    Dim colGroupedValues = From x In MyBase.Items Group x By Key = x.strDataName Into Group Select strName = Key, colValues = Group
    MyBase.Clear()
    For Each x In colGroupedValues
        MyBase.Add(x)
    Next
End Sub

当然,这不起作用,因为无法将x添加到ObservableCollection(Of itmDataDetails)中。有关如何完成此任务的任何建议?我不太了解LINQ,所以发现我做错了我不会感到惊讶。

先谢谢大家。

1 个答案:

答案 0 :(得分:1)

所以我想我在这里问错了。我真正想要的是将GridView中的每一列设置为itmDataDetails的DataName部分,并将其相应的记录设置为DataValue。

为此,我按照有用的指南进行了操作:http://weblogs.asp.net/psheriff/archive/2010/03/08/using-a-wpf-listview-as-a-datagrid.aspx

所以整个事情被替换为:

Private Sub FillDataList()
   Dim strConnectionString As String = "INSERT CONNECTION INFO HERE"
   Dim strCommandString As String = "INSERT QUERY HERE"
   Dim objCommand As New OleDb.OleDbCommand(strCommandString)
   Dim objConnection As New OleDb.OleDbConnection(strConnectionString)
   Dim objAdapter As New OleDb.OleDbDataAdapter
   Dim ds As New DataSet

   objConnection.Open()
   objAdapter.SelectCommand = objCommand
   objCommand.Connection = objConnection
   objAdapter.Fill(ds)
   lsvData.View = BuildDataView(ds)
   lsvData.DataContext = ds.Tables(0)
   lsvData.SetBinding(ListView.ItemsSourceProperty, New Binding)
   objConnection.Close()

End Sub

Public Function BuildDataView(ByVal ds As DataSet) As GridView
    Dim gv As New GridView
    For Each item As DataColumn In ds.Tables(0).Columns
        Dim gvc As New GridViewColumn
        gvc.DisplayMemberBinding = New Binding(item.ColumnName)
        gvc.Header = item.ColumnName
        gvc.Width = [Double].NaN
        gv.Columns.Add(gvc)
    Next
    Return gv
End Function

这给了我想要的东西。对不起,如果有任何误解的话。我仍然会接受一个比我的解决方案(慈善等)更好地完成这项任务的答案

我也怀疑数据库引擎在这里没关系,所以你可能会为Oracle数据库做类似的事情。