Linq中的ToList()和CopyToDataTable()

时间:2023-03-09 23:10:25
Linq中的ToList()和CopyToDataTable()

最近在项目中使用了Linq,想把Linq的查询结果直接转换成DataTable对象,通过查找发现Linq有一个CopyToDataTable<T>的泛型方法,该方法只能在T是DataRow的情况下使用,发现了这个方法以后就直接在项目中使用了,但是在使用的过程中发现,如果Linq的查询结果不包含任何DataRow对象的时候,使用CopyToDataTable()方法会报错,代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient; namespace CopyToDataTableDemo
{
class Program
{
static void Main(string[] args)
{
string strConn = ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strConn))
{
string strSQL = "SELECT * FROM Product";
SqlCommand cmd = new SqlCommand(strSQL, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
try
{
DataTable dt = new DataTable();
adapter.Fill(dt);
//CopyToDataTable()
DataTable dtTemp = dt.AsEnumerable().Where<DataRow>(p =>
{
return p["ProductId"].ToString().Trim().Equals("");
}).CopyToDataTable(); }
catch (Exception ex)
{ }
finally
{
conn.Close();
}
}
}
}
}

报错信息如下:

Linq中的ToList()和CopyToDataTable()

该错误信息说明如果Linq的查询结果不包含任何DataRow对象的时候,使用该方法会报错,那么怎么将Linq的查询结果转换成DataTable使用呢?

继续查询Linq的方法,发现Linq还有一个ToList()的方法,使用该方法可以解决Linq查询结果不包含任何DataRow对象时报错的问题,代码修改如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient; namespace CopyToDataTableDemo
{
class Program
{
static void Main(string[] args)
{
string strConn = ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strConn))
{
string strSQL = "SELECT * FROM Product";
SqlCommand cmd = new SqlCommand(strSQL, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
try
{
DataTable dt = new DataTable();
adapter.Fill(dt);
//CopyToDataTable()
// 当LINQ的查询结果不包含任何DataRow对象的时候会报错
//DataTable dtTemp = dt.AsEnumerable().Where<DataRow>(p =>
//{
// return p["ProductId"].ToString().Trim().Equals("4");
//}).CopyToDataTable(); //ToList()
List<DataRow> list = dt.AsEnumerable().Where<DataRow>(p =>
{
return p["ProductId"].ToString().Trim().Equals("");
}).ToList();
if (list.Count > )
{
DataTable dtTemp = dt.Clone();
// 循环遍历list转换成DataTable
list.ForEach(p =>
{
dtTemp.Rows.Add(p.ItemArray);
});
} }
catch (Exception ex)
{ }
finally
{
conn.Close();
}
}
}
}
}

使用ToList()方法就可以解决该报错问题了。