如何在DataTable中获取唯一值

时间:2015-01-21 18:19:20

标签: c# sql linq 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);
    }
}

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

1 个答案:

答案 0 :(得分:1)

您可以LINQ使用DataTable

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);