Bonjour.
Je suis un peu rouillé sur les DataTable et confronté à deux problèmes.
soit le code suivant :qui est censé faire :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 private static DataSet MergeTableLignesByField(DataSet dataSet, DataTable originalTable, int columnIndex) { if(originalTable.Rows.Count > 0 && originalTable.Rows[0].ItemArray[columnIndex] is string) { DataTable newTable = originalTable.Clone(); newTable.Clear(); DataRow previousRow = null; for(int i = 0; i < originalTable.Rows.Count; i++) { DataRow currentRow = originalTable.Rows[i]; bool matchLine = false; if(previousRow != null) { // On compare les champs de deux lignes pour savoir si on peut les fusionner : tous les champs sont identiques sauf le champ spécifié for(int j = 0; j < currentRow.ItemArray.Length; j++) if(j != columnIndex) { matchLine = (currentRow.ItemArray[j].ToString() == previousRow.ItemArray[j].ToString()); if(!matchLine) break; } //Si les lignes sont identiques, on peut les fusionner et merger le champ voulu. if(matchLine) { previousRow.BeginEdit(); string newValue = string.Concat(previousRow.ItemArray[columnIndex].ToString(), " | ", currentRow.ItemArray[columnIndex].ToString()); previousRow.ItemArray[columnIndex] = newValue; previousRow.AcceptChanges(); previousRow.EndEdit(); } } if(!matchLine) { if(previousRow != null) newTable.Rows.Add(previousRow.ItemArray); previousRow = newTable.NewRow(); previousRow.ItemArray = currentRow.ItemArray; } } //originalTable.Clear(); //originalTable.Merge(newTable, true); } return dataSet; }
Dans une table d'un DataSet, parcourir toutes les lignes successives, si on trouve plusieurs lignes avec les mêmes valeurs (sauf pour le champ indiqué par columnIndex) on ne prend qu'une ligne et on concatène le contenu du champ [columnIndex] de toutes les lignes qui matches.
C'est clair ?
Premier problème : previousRow.ItemArray[columnIndex] = newValue; ne change pas de valeur.
2ème pbm : c'est une usine à gaz... Il n'y aurait pas plus simple ?
Merci
p.s. :
mes données sont du genre :
et je veux fusionner les lignes 1 & 2 , et 3 & 4nom1,prénom1,champ à concat 1, integer
nom1,prénom1,champ à concat 2, integer
nom2,prénom2,champ à concat 1, integer
nom2,prénom2,champ à concat 2, integer
nom3,prénom3,"texte", integer
Partager