我有一个数据集objds,它包含名为Table1的表。 Table1包含名为ProcessName的列。这个ProcessName包含重复的名称。所以我想只选择不同的名称。是否可能?
intUniqId[i] = (objds.Tables[0].Rows[i]["ProcessName"].ToString());
class DataTableHelper
{
public DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
{
DataTable dt = new DataTable(TableName);
dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);
object LastValue = null;
foreach (DataRow dr in SourceTable.Select("", FieldName))
{
if ( LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])) )
{
LastValue = dr[FieldName];
dt.Rows.Add(new object[]{LastValue});
}
}
return dt;
}
private bool ColumnEqual(object A, object B)
{
// Compares two values to see if they are equal. Also compares DBNULL.Value.
// Note: If your DataTable contains object fields, then you must extend this
// function to handle them in a meaningful way if you intend to group on them.
if ( A == DBNull.Value && B == DBNull.Value ) // both are DBNull.Value
return true;
if ( A == DBNull.Value || B == DBNull.Value ) // only one is DBNull.Value
return false;
return ( A.Equals(B) ); // value type standard comparison
}
}
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
//data is a DataTable that you want to change
DataTable result = data.AsEnumerable().Distinct().CopyToDataTable < DataRow > ();
这仅适用于asp.net 4.0 ^框架,需要引用System.Data.DataSetExtensions,正如Ivan Ferrer Villa所指出的那样。
System.Data.DataSetExtensions
。 - Ivan Ferrer Villavar ValuetoReturn = (from Rows in YourDataTable.AsEnumerable()
select Rows["ColumnName"]).Distinct().ToList();
DataTable dt = new DataTable("EMPLOYEE_LIST");
DataColumn eeCode = dt.Columns.Add("EMPLOYEE_CODE", typeof(String));
DataColumn taxYear = dt.Columns.Add("TAX_YEAR", typeof(String));
DataColumn intData = dt.Columns.Add("INT_DATA", typeof(int));
DataColumn textData = dt.Columns.Add("TEXT_DATA", typeof(String));
dt.PrimaryKey = new DataColumn[] { eeCode, taxYear };
它根据eecode和taxyear的组合来过滤数据表,被视为唯一。
objds.Table1.Select(r => r.ProcessName).AsEnumerable().Distinct();
DataTable dtbs = new DataTable();
DataView dvbs = new DataView(dt);
dvbs.RowFilter = "ColumnName='Filtervalue'";
dtbs = dvbs.ToTable();
类似这样的东西?
从表中选择不同的...根据条件 WHERE 进行筛选。
http://www.felixgers.de/teaching/sql/sql_distinct.html
注意:这是一个作业问题?感谢上帝有谷歌。