选择DataTable中的唯一值(Distinct)-.Net技术-3P代码网
繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> 选择DataTable中的唯一值(Distinct)

选择DataTable中的唯一值(Distinct)

2007-10-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:开发中经常用到筛选DataTable等数据源中的唯一值(类似SQL中Distinct的返回结果),在.NET FX 1.x下我是这写的: 1static DataTable SelectDistinct(string ReturnTableName, DataTable SourceTable, string Ret...

开发中经常用到筛选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(true, new string[] { "ColumnName" });

责任编辑:admin
相关文章