2012-10-27 2 views
0

나는 데이터베이스에서 다음 데이터를 가져 오는 DataTable이 있습니다.LINQ로 DataTable을 필터링하는 방법

  • Name
  • Address
  • CountryID

내가 LINQ가 내 옆에있는 데이터를 필터링 할 : 나는 ID가 1, 2, 3, 4 개국이있는 체크 박스 목록이 나는 확인 된 국가의 결과 만 얻고 싶다. 예 : 1, 2, 4를 LINQ 별 국가 ID로 사용합니다. 그리드보기에 바인딩하고 싶습니다. 나는 다음과 같은 코드를 사용하고

:

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(); 

희망! 이 같은

관련 문제