2014-09-19 40 views
0

我從強類型數據集中獲取某種類型的數據表對象,現在我想知道列「標題」中是否有某個字符串在其中。在數據表中搜索一個字符串列

我想這個,有沒有更好的方法?

FruitDataAccess fda = new FruitDataAccess(); 
    FruitDataTable fdt = cda.GetFriuts(fruitCrateID); 
    DataTable dt = fdt.CopyToDataTable(); 
    var row = dt.Rows.Cast<DataRow>().Any(r => r.ItemArray.Any(c => c.ToString().Contains("whatever"))); 
+3

你有一個'使用System.Linq的'? – sisve 2014-09-19 14:18:00

+0

我添加了對System.Linq的引用,但是當我單擊Cast來自動添加引用時,它不會說添加引用,讓我試試 – Mathematics 2014-09-19 14:18:43

+0

@CustomizedName,它是一種擴展方法。您將無法在Visual Studio中解決問題。你必須在你的代碼中明確地指定'使用System.Linq;' – Habib 2014-09-19 14:19:18

回答

2

使用LINQ TO DataSet/DataTable像:

var search = dt.AsEnumerable() 
       .FirstOrDefault(r=> r.Field<string>("Title") == "your string"); 

if(search != null) 
{ 
    //found 
} 

您還可以找到與你的病情像行:

DataRow[] foundRows; 
foundRows = dt.Select("Title Like '%your string%'"); //similar to Contains 

參見:How to: Locate a Specific Row in a DataTable

+1

很好,你有Skype? – Mathematics 2014-09-19 14:26:36

相關問題