2011-12-06 88 views
1

我有一個包含3000條記錄的DataTable。我想在Android SQLite & MS SQL之間進行復制。我想將數據集轉換爲JSON。我無法傳遞這麼多的數據。所以我想第一次拿500條記錄第二次500條記錄。同樣想做。所以我使用Linq從DataTable中選擇記錄。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行。

+0

是您的解決方案嗎? –

回答

1

我相信你的錯誤實際上

是源不包含任何數據行。

由於@Pranay林蛙提到,查詢並沒有真正執行,直到調用CopyToDataTable,但那時的表是空的:如果刪除調用Rows.Clear()

dtDownloadJson.Rows.Clear(); 
dt1 = query1.CopyToDataTable(); 

,您應該CopyToDataTable()跑。

+0

是的。它返回結果。謝謝 – Piraba