Linq:从DataTable中选择行
本文关键字:选择 DataTable Linq | 更新日期: 2023-09-27 18:17:05
我有一个包含3000条记录的DataTable。我想在Android SQLite之间进行复制MS SQL。我想将Dataset转换为JSON。我不能传递那么多数据。所以我想第一次拿500张唱片,第二次再拿500张唱片。同样想做。因此,我使用Linq从DataTable中选择记录。
public String ConverDataSetToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
int start = 0;
int end =500;
int chk = 0;
string json = "";
int currentChk = currentSplit;
int total =0;
DataTable dt1 = new DataTable();
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
total = dtDownloadJson.Rows.Count;
// If row count less than 500, then take that amount
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
//number of split data set
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
var AllProducts = dtDownloadJson.AsEnumerable();
if (AllProducts.Count() > 0)
{
var query1 = (from c in AllProducts select c).Skip(0);
query1 = (from c in query1 select c).Take((end - start) + 1);
int res = query1.Count();
Console.WriteLine("---------" + res);
if (query1.Count() > 0)
{
dtDownloadJson.Rows.Clear();
dt1 = query1.CopyToDataTable();
int count = dt1.Rows.Count;
json = JsonConvert.SerializeObject(dt1, Formatting.Indented);
}
}
}
}
return json;
}
请帮助我,这给出了一个错误的The Source contain no data source. When Go to CopyToDataTable
行。
我相信你的错误实际上是
源文件不包含datarow
正如@Pranay Rana提到的,你的查询实际上并没有执行,直到你调用CopyToDataTable
,但到那时表是空的:
dtDownloadJson.Rows.Clear();
dt1 = query1.CopyToDataTable();
如果您删除对Rows.Clear()
的调用,您的CopyToDataTable()
应该运行。