如何在 DataTable 中获取唯一值

How to get unique value in a DataTable

我有以下代码:

string strQuery = "";

using (SqlConnection scCon = new SqlConnection(connString))
{
    using (SqlCommand scCmd = new SqlCommand("locZ", scCon))
    {
        SqlDataAdapter sda = new SqlDataAdapter();
        DataTable dt = new DataTable();
        scCmd.CommandType = CommandType.StoredProcedure;

        scCmd.Parameters.Add("@Loc", SqlDbType.VarChar).Value = Loc.SelectedItem.Value;

        sda.SelectCommand = scCmd;
        sda.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            strQuery += dr["Spec"].ToString() + "<br />";
        }

        Label1.Text = strQuery;

        Session.Add("DTTa", dt);
    }
}

如何修改代码以便我只获得该列的唯一值?

您可以使用 LINQDataTable:

var distinctRows = dt.AsEnumerable()
                     .GroupBy(row => row.Field<string>("Spec"))
                     .Select(g => g.First());

foreach (DataRow dr in distinctRows) 
{
}

您可以使用 DistinctBy 方法使其更短、更高效:

var distinctRows = dt.AsEnumerable()
                     .DistinctBy(row => row.Field<string>("Spec"));

如果您只想获取一列的值并将它们连接起来,您甚至不需要 foreach:

var distinctValues = dt.AsEnumerable()
                       .Select(row => row.Field<string>("Spec"))
                       .Distinct();
Label1.Text = string.Join("<br />", distinctValues);