I have a SQL Query like this
SELECT DISTINCT CustomerName FROM Customers
It is returning list of distinct customerNames,
How can I get this in list in C#
Currently I am getting the result in DataTable and then extract in list for only my required column.
private List<String> GetDistinctCustomerNames()
{
var dataTable = new DataTable("ResultDataTable");
using (var sqlCommand = new SqlCommand())
{
// set the connection for the commnad
sqlCommand.Connection = sqlConnection;
// assign the insert query as a text to the sql command
sqlCommand.CommandText = "SELECT DISTINCT CustomerName FROM Customers";
using (var sqlDataAdapter = new SqlDataAdapter())
{
sqlDataAdapter.SelectCommand = sqlCommand;
dataTable.Load(sqlCommand.ExecuteReader());
}
if (dataTable.Columns.Contains("CustomerName"))
{
return (from DataRow dataRow in dataTable.Rows select dataRow["CustomerName"].ToString()).ToList();
}
return null;
}
but I don't feel it is a good solution.