2011-11-28 64 views
0

這是我的代碼:如何從DataView中選擇包含所有記錄的前5條記錄以降序排列?

DataSet dsCategoryRes = new DataSet(); 
dsCategoryRes = oCourse.SubscribedResources(Profile.UserName, CustomerId, "0", 0); 
DataTable dt = dsCategoryRes.Tables[0]; 
DataView dv = new DataView(dt); 


Int32 maxCnt; 
if (dv.Table.Rows.Count <= 5) 

    maxCnt = dv.Table.Rows.Count - 1; 

else 

    maxCnt = 4; 
int cnt; 
for (cnt = 0; cnt <= maxCnt; cnt++) 
{ 

    dv.Sort = "CategoryName DESC"; 
    //dv.Table.Rows.Cast<System.Data.DataRow>().Take(5); 

    dt = dv.ToTable(); 
    dt.Rows.Cast<System.Data.DataRow>().Take(5); 
    rptSub.DataSource = dt; 


    rptSub.DataBind(); 
} 

使用此點到能夠在降序排序,但是我不能夠選擇前5個值。

回答

0

像這樣?

var dt = new DataTable(); 

dt.Columns.Add("ID", typeof(Int32)); 
dt.Columns.Add("Name"); 
//Creating some dummy data 
for (int i = 0; i < 10; i++) 
{ 
    var newRow = dt.NewRow(); 
    newRow["ID"] = i; 
    newRow["Name"] = "dummyData" + i; 
    dt.Rows.Add(newRow); 
} 

var dt2 = new DataTable(); 
dt2 = (from rows in dt.AsEnumerable().OrderByDescending(x => x.Field<int>("ID")) select rows).Take(5).CopyToDataTable(); 
+0

這應該在字段「ID」上對原始數據表進行排序。然後它應該選擇前五個,然後創建一個新的數據副本,您可以將其直接設置爲數據源,或者將其分配給不同的數據表中,如示例中所示 –

相關問題