Distinct IDs from DataSet






2.11/5 (8 votes)
An article on selecting distinct values from a DataSet.
Introduction
Sometimes we need to find out the distinct values in a row in a DataSet
but ADO.NET doesn't provide any Select or other functions to do this. So we can implement a similar kind of functionality using the code snippet given in this article.
Background
I was working on a project and found that we can't get distinct IDs from a DataSet
, which was required in some cases. So I have written a code snippet which may help you.
Using the code
The code is self explanatory, and contains comments.
/// <summary>
/// Gives the uniqueId list from the rows
/// of the table which satisfy the given condition.
/// </summary>
/// <param name="dtSource">The source table from
/// which rows will be selected.</param>
/// <param name="IDColumnName">The ID column name
/// which will be created as list.</param>
/// <param name="Condition">The condition
/// based upon which rows will be selected.
/// If one wants to check all rows pass Condition as ""</param>
/// <returns>List of unique ids as string list
/// which satisfy the given condition</returns>
public List<string> GetDistinctIDs(DataTable dtSource,
string IDColumnName, string Condition)
{
List<string> arUniqueId = new List<string>();
foreach (DataRow dr in dtSource.Select(Condition))
{
if(dr[IDColumnName] == DBNull.Value ||
arUniqueId.Contains(dr[IDColumnName].ToString()))
{
continue;
}
arUniqueId.Add(dr[IDColumnName].ToString());
}
return arUniqueId;
}
/// <summary>
/// Gives the unique value rows from the rows
/// of the table which satisfy the given condition.
/// </summary>
/// <param name="dtSource">The source table
/// from which rows will be selected.</param>
/// <param name="IDColumnName">The ID column
/// name which will be created as list.</param>
/// <param name="ValueColumnName">The Value column name which
/// will be created as Value in Hashtable.</param>
/// <param name="Condition">The condition based
/// upon which rows will be selected.
/// If one wants to select all rows pass Condition as ""
/// </param>
/// <returns>A Hashtable Containing unique keys
/// as Ids and Value corresponds to them.</returns>
public Hashtable GetDistinctValues(DataTable dtSource, string IDColumnName,
string ValueColumnName, string Condition)
{
Hashtable ht = new Hashtable();
foreach (DataRow dr in dtSource.Select(Condition))
{
if (dr[IDColumnName] == DBNull.Value ||
ht.ContainsKey(dr[IDColumnName]))
{
continue;
}
ht.Add(dr[IDColumnName],dr[ValueColumnName]);
}
return ht;
}
Points of Interest
You can use this code snippet in many ways. The hash table is one way of implementation. If you want to implement multi-column values, then probably you can create a simple table instead of the Hashtable
and add the rows and fill the values in the DataTable
.
History
- Ver. 1.0 by Mahendra.