我有像这样的SQL查询
SELECT DISTINCT CustomerName FROM Customers
它返回了不同customerNames的列表,
如何在C#
中列出这个目前我在DataTable中获取结果,然后在列表中仅提取我所需的列。
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;
}
但我觉得这不是一个好的解决方案。
答案 0 :(得分:1)
您应该googling或更多 https://stackoverflow.com/a/19406319/2089368 ......
答案 1 :(得分:0)
而不是让你回来,我会做一个foreach
ForEach(var element in DataTable.Rows)
if(element.CustomerName != NULL)
list.add(element.ToString())
//To string is only needed if the db stores it as not an nvarchar or something like that
return list
答案 2 :(得分:0)
从方法中获取列表后,您可以应用以下代码。
// Get distinct elements and convert into a list again.
List<string> distinct = list.Distinct().ToList();