by Edward
26 July 2010 08:22
The LINQ distinct select method is a powerful small method that can help you select unique entries from datatable.
The following example will return a datatable with unique results, from a datatable which can be populated from a database. The following example uses a datatable I created to show you how the LINQ distinct select method works.
The example below have a list of users, but I only want the 'user names' to be returned. They have to be unique, as I might want to use it in a report.
/// <summary>
/// Gets the user names.
/// </summary>
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 - this blog entry is created to show you how easy it can be to use LINQ with C# code.