从DataSet 中获取不同的 ID






2.11/5 (8投票s)
一篇关于从 DataSet 中选择不同值的文章。
引言
有时我们需要找出 DataSet
中某行中的不同值,但 ADO.NET 没有提供 Select 或其他函数来执行此操作。因此,我们可以使用本文给出的代码片段来实现类似的功能。
背景
我正在一个项目上工作,发现我们无法从 DataSet
中获取不同的 ID,这在某些情况下是必需的。因此,我编写了一个代码片段,希望能对您有所帮助。
使用代码
代码自明,包含注释。
/// <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;
}
关注点
您可以使用此代码片段进行多种用途。哈希表是一种实现方式。如果您想实现多列值,那么您可能可以创建一个简单的表,而不是 Hashtable
,并添加行并在 DataTable
中填充值。
历史
- 1.0 版,作者:Mahendra。