我認爲我的問題是一個經典問題,但我無法獲得實施解決方案的正確方法。所以我會在SOF這裏問一下。在集合中表示類似數據的表格的最佳方式
我需要將一些數據導出到一個CSV文件,其中包含表頭和值。爲了獲得我需要迭代一個集合的數據。集合中的每個項目都有一個屬性,其中包含一組鍵/值對。密鑰包含標題。並非每個鍵/值對的集合都具有相同的大小。
當遍歷鍵/值對時,我收集集合中的所有可能的標題。當您收到其他密鑰/值的集合並找到未知密鑰時,此集合將被擴展。發生這種情況時,您需要確保將相應的值寫入CSV文件的正確標題下。我試圖使用標題集合中標題的索引,但我似乎無法使它工作。我曾想過多維數組,鋸齒形數組和字典組合。
對於我的解決方案,我不想在查找右欄時在標題和鍵之間進行字符串比較。這似乎沒有必要。我認爲,兩個循環和索引應該這樣做。
好的,這是我到目前爲止的代碼。這僅適用於外循環中的1個項目,因爲ArrayList一次僅消費一個,而不消費任何給定的索引。當在外部循環的索引12處添加到頭集合的新項目時,循環的值集合還沒有索引12。所以我得到一個索引越界。所以我想創建一個頭像arraylist大小的值arraylist,但這也不起作用。
Private Shared Function GetData(listItems As SPClient.ListItemCollection) As ArrayList
'first store all values and make sure keys and values are matched
Dim resultsToStore As ArrayList = New ArrayList()
Dim headersToStore As ArrayList = New ArrayList()
resultsToStore.Add(headersToStore)
Dim totalListItems = listItems.Count
Dim fieldNotToStore = ConfigurationService.FieldValuesNotToStore
Dim displaynames = ConfigurationService.FieldValueDisplayNames
For index As Integer = 0 To totalListItems - 1
Dim valuesToStore As ArrayList = New ArrayList()
Dim item As SPClient.ListItem = listItems(index)
Dim fieldValues = item.FieldValues
For Each fieldValue In fieldValues
If (Not fieldNotToStore.Contains(fieldValue.Key)) Then 'If it is not in this collection is must be stored
Dim headerIndex = headersToStore.IndexOf(fieldValue.Key) 'does this key exist in the headersArray
If (headerIndex = -1) Then 'If fieldValue.Key is already in the array it doesn't need to be stored again (-1 = no index found)
Dim displayname = String.Empty
If (displaynames.ContainsKey(fieldValue.Key)) Then
displayname = displaynames.Item(fieldValue.Key)
Else
displayname = fieldValue.Key.ToString
End If
headerIndex = headersToStore.Add(displayname) '' Add new header
End If
valuesToStore.Insert(headerIndex, fieldValue.Value.ToString) 'use headerindex to match key an value
End If
Next
resultsToStore.Add(valuesToStore)
Next
Return resultsToStore
End Function
我認爲這個問題已經解決了像一千倍,所以請善待。
更新:如果你有任何其他(主流)語言的答案比vb.net還好,但我更喜歡vb.net和C#,因爲它們都在.net框架上。
謝謝
感謝您的評論。我知道這種方法是漫長的。我等待重構,直到後來。我想先工作,但也許你是正確使用班級,可能是一種方式。我使用arraylist,因爲它根據需要擴展。通用列表也是這樣做的,它並沒有真正改變。 – Sigur
仔細查看您的解決方案:1.您的類ValueStore看起來像一本字典,然後ResultStore看起來像一個字典列表。爲什麼不使用這些? 2.即使在您的解決方案中,語句valuesToSore.Insert(....)也會導致錯誤。 – Sigur
我用你的意見作爲靈感。所以謝謝。那麼我現在有更多的OO。非常感謝你的麻煩。 – Sigur