去除DataTable中重复字段
/// <summary>
/// </summary>
/// <param name="SourceTable"></param>
/// <param name="FieldNames"></param>
/// <returns></returns>
protected DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
{
object[] lastValues;
DataTable newTable;
DataRow[] orderedRows;
//if (FieldNames == null || FieldNames.Length == 0)
// throw new ArgumentNullException("FieldNames");
//如果FieldNames为空,则默认查询所有的列。
if (FieldNames == null || FieldNames.Length == 0)
{
FieldNames = new string[SourceTable.Columns.Count];
for (int i = 0; i < SourceTable.Columns.Count; i++)
{
FieldNames[i] = SourceTable.Columns[i].ColumnName;
}
}
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]];
}
#endregion
调用如下:
DataTable tbl = new DataTable();
tbl.Columns.Add("Id", typeof(System.Int32));
tbl.Columns.Add("City", typeof(System.String));
tbl.Columns.Add("Province", typeof(System.String));
tbl.Rows.Add(1, "武汉", "湖北");
tbl.Rows.Add(2, "应城", "湖北");
tbl.Rows.Add(3, "武汉", "湖北");
// DataTable dt2 = SelectDistinct(tbl, null);
DataTable dt2 = SelectDistinct(tbl, "City", "Province" );
//DataTable dt2 = SelectDistinct(tbl, new string[] { "City", "Province" });
this.dataGridView1.DataSource = dt2;
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET