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.
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;
}
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