簡體   English   中英

如何使用LINQ過濾DataTable

[英]How to filter DataTable with LINQ

我有DataTable ,它帶給我以下數據庫中的數據。

  • Name
  • Address
  • CountryID

我想用LINQ過濾我這邊的數據:我有一個復選框列表,其中包含ID為1、2、3、4的國家/地區。我只想獲取被檢查國家/地區的結果。 例如,LINQ將1、2、4作為CountryID。 我想將其綁定到網格視圖。

我正在使用以下代碼:

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

嘗試這樣的事情:

// 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.

您應該嘗試以下一種方法:

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

希望這會有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM