- Logic:
/// <summary>/// Selects the distinct from data table. /// </summary> /// <param name="TableName">Name of the table.</param> /// <param name="SourceTable">The source table.</param> /// <param name="FieldName">Name of the field.</param> /// <returns></returns> public static DataTable DistinctDataFromDataTable(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; } /// <summary> /// Columns the equal. /// </summary> /// <param name="A">The A.</param> /// <param name="B">The B.</param> /// <returns></returns> private static 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 }
Example:
public static void GetUserNames() - {
- DataTable dt = new DataTable();
- dt.Columns.Add("UserId", typeof(int));
- dt.Columns.Add("UserName", typeof(string));
- dt.Rows.Add(1, "Joe Smith");
- dt.Rows.Add(2, "John Doe");
- dt.Rows.Add(3, "Joe Smith");
- dt.Rows.Add(4, "Jane Smith");
- dt.Rows.Add(5, "Jane Doe");
- DataTable filterTable = GetUniqueEntries(dt);
- }
- /// <summary>
- /// Gets the unique entries.
- /// </summary>
- /// <param name="dt">DataTable</param>
- /// <returns></returns>
- private static DataTable GetUniqueEntries(DataTable dt)
- {
- var query = (
- from row in dt.AsEnumerable()
- select row.Field<string>("UserName")).Distinct();
- DataTable dtDistinctNames = new DataTable();
- dtDistinctNames.Columns.Add("UserName", typeof(string));
- //have to return a datatable, thus loop through entries
- foreach (string item in query)
- {
- DataRow newRow = dtDistinctNames.NewRow();
- newRow["UserName"] = item;
- dtDistinctNames.Rows.Add(newRow);
- }
- return dtDistinctNames;
- }
This code snippet will return you a list of users where 'username' are unique. There eliminating duplicate names from the list. There are alternative ways to do this type of functionality
Sunday, April 28, 2013
Select unique rows from a DataTable
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment