项目必须引用System.Data.DataSetExtensions.dll以加载扩展
SQL Server 数据表内容如下
try
{
using (SqlConnection conn = new SqlConnection(SqlHelper.GetConnSting()))
{
string strSql = "SELECT * FROM dbo.Account";
DataTable dtTemp = SqlHelper.ExecuteDataset(conn, CommandType.Text, strSql).Tables[0];
textBox1.Clear();
//此方式不能转化为datatable进行绑定
var accounts = from account in dtTemp.AsEnumerable()
where account.Field<string>("FirstName") == "Adam"
select new
{
FirstName = account.Field<string>("FirstName"),
LastName = account.Field<string>("LastName")
};
foreach (var account in accounts)
{
textBox1.AppendText(string.Format("{0}-{1}{2}", account.FirstName, account.LastName, Environment.NewLine));
}
//使用此方式可将accounts转化为datatable进行绑定
var accountsA = from account in dtTemp.AsEnumerable()
where account.Field<string>("FirstName") == "Adam"
select account;
dataGridView1.DataSource = accountsA.CopyToDataTable();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
结果如下