选择DataTable中的唯一值(Distinct)
开发中经常用到筛选DataTable等数据源中的唯一值(类似SQL中Distinct的返回结果),在.NET FX 1.x下我是这写的:
再后来又这样写:
1
static DataTable SelectDistinct(string ReturnTableName, DataTable SourceTable, string ReturnFieldName, string AdditionalFilterExpression)
2
{
3
DataTable dt = new DataTable(ReturnTableName);
4
dt.Columns.Add(ReturnFieldName, SourceTable.Columns[ReturnFieldName].DataType);
5
object LastValue = null;
6
foreach (DataRow dr in SourceTable.Select("", ReturnFieldName))
7
{
8
if (LastValue == null || !(ColumnEqual(LastValue, dr[ReturnFieldName])))
9
{
10
LastValue = dr[ReturnFieldName];
11
dt.Rows.Add(new object[] { LastValue });
12
}
13
}
14
if (ds != null)
15
ds.Tables.Add(dt);
16
return dt;
17
}
18
19
static bool ColumnEqual(object A, object B)
20
{
21
// Compares two values to see if they are equal. Also compares DBNULL.Value.
22
// Note: If your DataTable contains object fields, then you must extend this
23
// function to handle them in a meaningful way if you intend to group on them.
24
25
if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
26
return true;
27
if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
28
return false;
29
return (A.Equals(B)); // value type standard comparison
30
}
31
后来这样写:
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

1
private DataTable SelectDistinct(DataTable sourceTable, string sourceColumn)
2
{
3
DataTable result = null;
4
try
5
{
6
result = new DataTable();
7
result.Columns.Add(sourceColumn, sourceTable.Columns[sourceColumn].DataType);
8
Hashtable ht = new Hashtable();
9
foreach (DataRow dr in sourceTable.Rows)
10
{
11
if (!ht.ContainsKey(dr[sourceColumn]))
12
{
13
ht.Add(dr[sourceColumn], null);
14
DataRow newRow = result.NewRow();
15
newRow[sourceColumn] = dr[sourceColumn];
16
result.Rows.Add(newRow);
17
}
18
}
19
return result;
20
}
21
catch (System.Exception ex)
22
{
23
ExceptionManager.Publish(ex);
24
return null;
25
}
26
finally
27
{
28
if (result != null)
29
result.Dispose();
30
}
31
}
32
33

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

再后来又这样写:
1
object[] distinctRoomType = GetDistinctValues(dt,"Roomtype");
2
3
Here is the method definition.
4
5
public object[] GetDistinctValues(DataTable dtable,string colName)
6
{
7
Hashtable hTable = new Hashtable();
8
foreach(DataRow drow in dtable.Rows)
9
{
10
try
11
{
12
hTable.Add(drow[colName],string.Empty);
13
}
14
catch{}
15
}
16
object[] objArray = new object[hTable.Keys.Count ];
17
hTable.Keys.CopyTo(objArray,0);
18
return objArray;
19
}
20
现在.NET FX 2.0中只要一句就可以搞定了,方便了许多:

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

1
DataTable d = dataSetName.dataTableName.DefaultView.ToTable(true, new string[] { "ColumnName" });
