亲爱的朋友: 今天是: 网站地图   |   加入收藏  |  设为首页 
零下七度07DU.com - 专业致力于网站建设和服务
首页关于我们付款方式七百易电子商务试用广告服务联系我们 
零下七度主页 网站建设 平面设计 软件开发 虚拟主机 域名注册 成功案例 文档中心 用户中心 帮助中心
    您的位置: 零下七度 >> 文档中心 >> .NET技术 >> Asp.net >> 在DataTable中实现DataTable.Select("Distinct")功能 
在DataTable中实现DataTable.Select("Distinct")功能
2006-12-11 22:52:42  作者:缘易姿姿Hermes Liu  来源:http://www.cnblogs.com/hermes262/archive/2006/12/05/583406.html
我们有时候需要对DataTable中数据进行Distinct处理,过滤掉重复的数据,本文给出了解决方法:



事例代码来源于:Erik Porter"s Blog Select DISTINCT on DataTable http://weblogs.asp.net/eporter/archive/2005/02/10/370548.aspx 以及 HOWTOVisualC # .NET 中实现 DataSet SELECTDISTINCT Helper 类http://support.microsoft.com/?id=326176



///

/// 返回执行Select distinct后的DataTable

///

/// 源数据表

/// 字段集

///


private DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)

{

object[] lastValues;

DataTable newTable;

DataRow[] orderedRows;



if (FieldNames == null || FieldNames.Length == 0)

throw new ArgumentNullException("FieldNames");



lastValues
= new object[FieldNames.Length];

newTable
= new DataTable();



foreach (string fieldName in FieldNames)

newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);



orderedRows
= SourceTable.Select("", string.Join(",", FieldNames));



foreach (DataRow row in orderedRows)

{

if (!fieldValuesAreEqual(lastValues, row, FieldNames))

{

newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));



setLastValues(lastValues, row, FieldNames);

}


}




return newTable;

}




private bool fieldValuesAreEqual(object[] lastValues, DataRow currentRow, string[] fieldNames)

{

bool areEqual = true;



for (int i = 0; i < fieldNames.Length; i++)

{

if (lastValues[i] == null || !lastValues[i].Equals(currentRow[fieldNames[i]]))

{

areEqual
= false;

break;

}


}




return areEqual;

}




private DataRow createRowClone(DataRow sourceRow, DataRow newRow, string[] fieldNames)

{

foreach (string field in fieldNames)

newRow[field]
= sourceRow[field];



return newRow;

}




private void setLastValues(object[] lastValues, DataRow sourceRow, string[] fieldNames)

{

for (int i = 0; i < fieldNames.Length; i++)

lastValues[i]
= sourceRow[fieldNames[i]];

}

使用:

DataTable dt=(System.Data.DataTable)this.ViewState["Mydt"];

string[] fileds={"Filed1","Filed2"};//DISTINCT字段数组

DataTable newdt=this.SelectDistinct(dt,fileds);//返回过滤后的DataTable

打印】【关闭】【收藏
零下七度07DU.COM - 文档中心


联系我们 - 关于我们 - 付款方式 - 汇款帐号 - 广告服务 - 网站地图 - 咨询反馈 - 招贤纳士 - 合作伙伴

地址:中国·四川·成都市锦江区仁居路2号 服务热线:028-85915526 联系我429459102 联系我13478148 联系我155040795 联系我605595956
广告商务:hermes262@163.com 客服:jarviseluo@yahoo.com.cn 投诉:xpxcc@hotmail.com
业务资质:中国万网2006核心合作伙伴;动易网络成都、西南区域代理商
零下七度 版权所有 备案编号:蜀ICP备06019771号
Copyright©2007 零下七度 07du.Com