2012-10-27 66 views
0

我有DataTable,它使我從數據庫中獲取數據。如何使用LINQ過濾DataTable

  • Name
  • Address
  • CountryID

我想通過LINQ過濾我這邊的數據:我有與ID爲1,2,3,4個國家複選框列表我只想得到被檢查國家的結果。例如1,2,4爲LINQ的CountryID。我想將它綁定到網格視圖。

我使用下面的代碼:

foreach (ListItem cBox in chkGodownlst.Items) 
{ 
    if (cBox.Selected) 
    { 
     var a = dt.AsEnumerable() 
        .Where(r => r.Field<int>("CountryID") == Convert.ToInt32(cBox.Value)); 
    } 
} 
+2

什麼是您遇到的問題? –

+0

我有多個檢查項目。所以我必須循環,並希望獲得所有的國家檢查數據列表 – Moiz

+0

你需要從dt獲得ienumerable?或從列表框?他們是否擁有相同的參考? – nawfal

回答

1

嘗試這樣:

// Get all checked id's. 
var ids = chkGodownlst.Items.OfType<ListItem>() 
    .Where(cBox => cBox.Selected) 
    .Select(cBox => cBox.Value) 
    .ToList(); 

// Now get all the rows that has a CountryID in the selected id's list. 
var a = dt.AsEnumerable().Where(r => 
    ids.Any(id => id == r.Field<int>("CountryID")) 
); 

// Create a new table. 
DataTable newTable = a.CopyToDataTable(); 

// Now set the new table as DataSource to the GridView. 
+0

我可以知道這個ID是什麼嗎? – Moiz

+0

@MoizKachwala你是什麼意思?你的意思是'ids'變量嗎? –

+0

代碼正在工作,但gridview沒有獲得列字段 – Moiz

0

你應該試試這個:

var collection = new List<dynamic>(); 
foreach (ListItem cBox in chkGodownlst.Items) 
{ 
    if(cBox.Selected) 
    { 
     collection.AddRange(dt.AsEnumerable().Where(r => r.Field<int>("CountryID") == Convert.ToInt32(cBox.Value))); 
    } 
} 

GridView1.DataSource = collection; 
GridView1.DataBind(); 

希望這將幫助!