如何将表的特定列添加到DataSet?

时间:2014-04-30 07:01:23

标签: c# dataset

我有一个包含五列的表TBL_Person

Person_ID, FirstName, LastName, Age, Location

我有一个返回数据集的方法:

public  DataSet GetPerson()
{
    SqlCommand _select = new SqlCommand();
    _select.CommandText = "SP-GetAllPerson";
    _select.CommandType = System.Data.CommandType.StoredProcedure;
    _select.Connection = Connection.GetConnection;

    SqlDataAdapter _daPerson = new SqlDataAdapter(_select);

    DataSet _personDs = new DataSet();
    _daCountry.Fill(_personDs, "[TBL_Person]");

    return _personDs;
}

此方法将返回包含以下列的数据集:

Person_ID, FirstName, LastName, Age, Location

但我希望我的方法返回一个包含以下列的数据集:

FirstName, LastName, Age

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果您不想选择所有列,请相应地更改存储过程。

如果您想在C#中进行更改,可以通过table.Columns.Remove(name)删除不需要的列:

public DataSet GetPerson(IEnumerable<string> wantedColumns)
{
    using(SqlConnection connection = new SqlConnection("Connection-String"))
    using (SqlDataAdapter _daPerson = new SqlDataAdapter("SP-GetAllPerson", connection))
    {
        _daPerson.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
        DataSet _personDs = new DataSet();
        _daPerson.Fill(_personDs, "TBL_Person");
        DataTable tblPersonIds = _personDs.Tables["TBL_Person"];
        var allColumns = tblPersonIds.Columns.Cast<DataColumn>().Select(c => c.ColumnName);
        // remove unwanted columns:
        foreach (string columnToRemove in allColumns.Except(wantedColumns))
            tblPersonIds.Columns.Remove(columnToRemove);
        return _personDs;
    }
}

您可以通过以下方式调用此方法:

DataSet dsPerson = GetPerson(new[]{"FirstName", "LastName", "Age"});

答案 1 :(得分:1)

如果您不想更改数据库中的SP,请更改.cs文件中的GetPerson()方法:

public DataSet GetPerson()
{
    SqlCommand _select = new SqlCommand();
    _select.CommandText = "SP-GetAllPerson";
    _select.CommandType = System.Data.CommandType.StoredProcedure;
    _select.Connection = Connection.GetConnection; 
    SqlDataAdapter _daPerson = new SqlDataAdapter(_select);
    DataSet _personDs = new DataSet();
    _daPerson.Fill(_personDs, "[TBL_Person]");
    _personDs.Tables["TBL_Person"].Columns.Remove("Person_ID");
    _personDs.Tables["TBL_Person"].Columns.Remove("Location");
    return _personDs;

}

否则,您可以相应地更改存储过程。

相关问题