This block of code is to implement a "Select Distinct" data row from a data table. The origin of this code is from http://weblogs.asp.net/eporter/archive/2005/02/10/370548.aspx and http://support.microsoft.com/?id=326176
Unfortunately I can't distinguish which one comes first so I credit both of them.
Here's the code.
Unfortunately I can't distinguish which one comes first so I credit both of them.
Here's the code.
1
private static DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
2
{
3
object[] lastValues;
4
DataTable newTable;
5
DataRow[] orderedRows;
6
7
if (FieldNames == null || FieldNames.Length == 0)
8
throw new ArgumentNullException("FieldNames");
9
10
lastValues = new object[FieldNames.Length];
11
newTable = new DataTable();
12
13
foreach (string fieldName in FieldNames)
14
newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);
15
16
orderedRows = SourceTable.Select("", string.Join(", ", FieldNames));
17
18
foreach (DataRow row in orderedRows)
19
{
20
if (!fieldValuesAreEqual(lastValues, row, FieldNames))
21
{
22
newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));
23
24
setLastValues(lastValues, row, FieldNames);
25
}
26
}
27
28
return newTable;
29
}
30
31
private static bool fieldValuesAreEqual(object[] lastValues, DataRow currentRow, string[] fieldNames)
32
{
33
bool areEqual = true;
34
35
for (int i = 0; i < fieldNames.Length; i++)
36
{
37
if (lastValues[i] == null || !lastValues[i].Equals(currentRow[fieldNames[i]]))
38
{
39
areEqual = false;
40
break;
41
}
42
}
43
44
return areEqual;
45
}
46
47
private static DataRow createRowClone(DataRow sourceRow, DataRow newRow, string[] fieldNames)
48
{
49
foreach (string field in fieldNames)
50
newRow[field] = sourceRow[field];
51
52
return newRow;
53
}
54
55
private static void setLastValues(object[] lastValues, DataRow sourceRow, string[] fieldNames)
56
{
57
for (int i = 0; i < fieldNames.Length; i++)
58
lastValues[i] = sourceRow[fieldNames[i]];
59
}
60
61

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

48

49

50

51

52

53

54

55

56

57

58

59

60

61
