选择DataTable中的唯一值(Distinct)

    开发中经常用到筛选DataTable等数据源中的唯一值(类似SQL中Distinct的返回结果),在.NET FX 1.x下我是这写的:
 1static DataTable SelectDistinct(string ReturnTableName, DataTable SourceTable, string ReturnFieldName, string AdditionalFilterExpression)
 2{
 3DataTable dt = new DataTable(ReturnTableName);
 4dt.Columns.Add(ReturnFieldName, SourceTable.Columns[ReturnFieldName].DataType);
 5object LastValue = null;
 6foreach (DataRow dr in SourceTable.Select("", ReturnFieldName))
 7{
 8if (LastValue == null || !(ColumnEqual(LastValue, dr[ReturnFieldName])))
 9{
10LastValue = dr[ReturnFieldName];
11dt.Rows.Add(new object[] { LastValue });
12}

13}

14if (ds != null)
15ds.Tables.Add(dt);
16return dt;
17}

18
19static 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
25if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
26return true;
27if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
28return false;
29return (A.Equals(B)); // value type standard comparison
30}

31
后来这样写:
 1private 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

再后来又这样写:
 1object[] distinctRoomType = GetDistinctValues(dt,"Roomtype");
 2
 3Here is the method definition. 
 4
 5public object[] GetDistinctValues(DataTable dtable,string colName)
 6{
 7Hashtable hTable = new Hashtable();
 8foreach(DataRow drow in dtable.Rows)
 9{
10try
11{
12hTable.Add(drow[colName],string.Empty);
13}

14catch{}
15}

16object[] objArray = new object[hTable.Keys.Count ];
17hTable.Keys.CopyTo(objArray,0);
18return objArray;
19}

20
现在.NET FX 2.0中只要一句就可以搞定了,方便了许多:
1DataTable d = dataSetName.dataTableName.DefaultView.ToTable(truenew string[] "ColumnName" });


posted on 2006-10-31 23:31  Zeus  阅读(2480)  评论(5编辑  收藏  举报

导航