2017-02-14 35 views
0

需要Linq的幫助。Linq Datatable子集使用group by和count> 1

我有一個數據表,它看起來像下面 I just have the W_text with me to search

使用上面的數據表,我想提取具有以下結果行的子集

The key to search is "First Employee"

所以你可以請參閱我想獲取那些W_Text值爲「First」和「Employee」但具有相同l_id的行的子集。

在數據庫術語中,這將是表1中的Select *,其中('First','Employee')組中的W_Text具有l_id> 1(或類似的東西)。

我如何在C#中使用數據表達到這一點?

我試着玩了下面的代碼,但是這也給了我整個datatable其他行。我不確定如何使用group by和having子句。如果有人能在這方面幫助我,我會說。

var results = from myRow in dtResult.AsEnumerable() 
       where myRow.Field<string>("W_Text") == "First" || 
        myRow.Field<string>("W_Text") == "Employee" 
       select myRow; 

dtCopy = results.CopyToDataTable(); 

回答

0

檢查以下內容:

 List<string> wTextFilter = new List<string>(); 
     wTextFilter.Add("First"); 
     wTextFilter.Add("Employee"); 

     // Get all Id's that satisfy all conditions:    
     List<int> results = dt.AsEnumerable() 
      // Get all Id's: 
      .Select(dataRow => dataRow.Field<int>("l_id")) 
      // Filter the Id's : 
      .Where(id => 
       // the Id should be greater than one. 
        id > 1 && 
        // check if all W_Text entries has a record in the datatable with the same Id. 
        wTextFilter.All(W_Text => dt.AsEnumerable().Any(dataRow => dataRow.Field<string>("W_Text") == W_Text && dataRow.Field<int>("l_id") == id))) 
        .Distinct().ToList(); 

     // Get all datatable rows filtered by the list of Id's. 
     DataTable dtCopy = dt.AsEnumerable().Where(dataRow => results.Contains((dataRow.Field<int>("l_id")))).CopyToDataTable(); 
+0

感謝Abdhulla。這也給了我一個包含所有「First」和「Employee」事件的數據集。我想只是那個「First」和「Employee」都有相同l_id的數據集,換句話說,其中count(l_id)大於1 – DevNovice

+0

在新編輯之後檢查上面顯示的代碼片段。 –

+0

工作出色! 非常感謝阿卜杜拉。真的很感謝你的迴應。 你能幫我理解代碼的工作原理嗎?我很難理解Linq,尤其是這些集合函數。 再次感謝! – DevNovice

0

嗨,你可以使用這樣如圖

var results = (from myRow in dtResult.AsEnumerable() 
       where myRow.Field<string>("W_Text") == "First" || 
       myRow.Field<string>("W_Text") == "Employee" 
       select myRow).ToLookup(item => item.Field<string>("l_id")); 

OR

var results = (from myRow in dtResult.AsEnumerable() 
       where myRow.Field<string>("W_Text") == "First" || 
       myRow.Field<string>("W_Text") == "Employee" 
       select myRow).GroupBy(item => item.Field<string>("l_id")).ToList(); 
+0

感謝您的快速反應瓦拉。 儘管現在顯示的結果數與子集相同,但我無法將副本複製到Datatable。你能告訴我如何遍歷結果變量嗎?當我們說話時,我也在擡頭,但是我們將非常感謝您的幫助。 – DevNovice

+0

抱歉的延遲,請檢查此鏈接http://stackoverflow.com/questions/24566246/linq-grouping-query-to-datatable – Vara

+0

再次感謝Vara,但您的迴應是返回所有l_id值包含文本「第一「或」員工「。我只想要包含「First」和「Employee」的唯一l_id。再次感謝 – DevNovice