2010-05-21 91 views
0

我想枚舉Linq查詢。下面我指定的例子。DataTable linq查詢迭代

EX:

DataTable _slidingDataTable = new DataTable("test"); 

for(int i=0; i<5;i++) 
{ 
    DataRow row = _slidingDataTable.NewRow(); 

    startPosition = DateTime.Now; 
    for(int i=0; i<5;i++) 
    { 
     _slidingDataTable.Columns.Add("TransferTime"); 
     row[columnName] = startPosition ; 
     _slidingDataTable.Columns.Add("TransferData"); 
     row[columnName] = "Test"+i; 
    } 

_slidingDataTable.Rows.Add(row); 
} 


var query1 = from myRow in _slidingDataTable.AsEnumerable() 
         where myRow.Field<DateTime>("TransferTime") == startPosition 
         select myRow; 

這個查詢輸出應該是行的集合。如何獲取收集行&迭代。

回答

1

在你的情況下,QUERY1是EnumerableRowCollection<DataRow>因爲你使用_slidingDataTable.AsEnumerable(),你可以遍歷它像這樣:

foreach (DataRow row in query1) 
{ 
    // Do stuff with that row 
} 
0

我給你舉個例子,通過它可以看到它,它也包括總和。

var drdatedisp = from row in dtfullreport.AsEnumerable() 
          group row by row.Field<string>("Order_Date") into g 
          select new 
          { 
           Order_Date = g.Key, 
           totalQnty = g.Sum(a => a.Field<int>("Item_Quantity")), 
           totalTax = g.Sum(a => float.Parse(a.Field<decimal>("TAXAMT").ToString())), 
           totalAmt = g.Sum(a => float.Parse(a.Field<decimal>("VALAMT").ToString())) 
          }; 
      DataTable dtdatedisp = new DataTable(); 
      dtdatedisp.Columns.Add("Order_Date"); 
      dtdatedisp.Columns.Add("Item_Quantity"); 
      dtdatedisp.Columns.Add("TAXAMT"); 
      dtdatedisp.Columns.Add("VALAMT"); 
      dtdatedisp.Rows.Clear(); 
      foreach (var g in drdatedisp) 
      { 
       DataRow newRow1 = dtdatedisp.NewRow(); 
       newRow1[0] = g.Order_Date; 
       newRow1[1] = g.totalQnty; 
       newRow1[2] = String.Format("{0:0.00}", g.totalTax); 
       newRow1[3] = String.Format("{0:0.00}", g.totalAmt); 
       dtdatedisp.Rows.Add(newRow1); 
      }