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
Started carreer with CEERI, Delhi, India as a C Programmer in 2004 and migrated my learning experiance to C#.Net in 2005 with DIGISIGN Noida, Joined Bally in 2006, worked with JK Technosoft since Jun 2007 till Apr 2009, joined back Bally in June 2009 and joined Misys in June 2010. Worked in different domains such as Casino Management, Digital Signage, and Medical and currently working M*Modal as Lead - Product Development.