2012-04-24 66 views
2

我有一個帶CheckedListBox的表單,用戶可以在其中選擇多個選項(它正在篩選目錄文件列表 - 篩選的文件出現在第二個列表框中)。在LINQ條件查詢中使用「或」

如果我有選擇的一組號碼,我可以在這樣的查詢使用「或」:

Dim query = From f As System.IO.FileInfo In StartList 
    Where f.Name.Contains("Romania") 
Where f.Channel = "Channel1" Or f.Channel = "Channel2" 

但隨着人可以點擊任意數量的選項(或沒有)我不能這樣做這個。 我已經嘗試了幾件事情,包括嘗試創建多個子查詢,然後對它們執行聯合,但是我無法使其工作。

這是到目前爲止我的代碼:

Dim Channels = ChannelListBox.CheckedItems 

    Dim query = From f As System.IO.FileInfo In StartList 
    Where f.Name.Contains("Romania") 

    If Channels.Count > 0 Then 

     Dim CurrentName As String = Channels(0).ToString 

     Dim Subquery = From g As System.IO.FileInfo In query 
       Where (g.Name.Contains(CurrentName)) 

     For i = 1 To Channels.Count - 1 

      CurrentName = Channels(i).ToString 
      Dim Subquery2 = From h As System.IO.FileInfo In query 
           Where (h.Name.Contains(CurrentName)) 

      Subquery = Subquery.Union(Subquery2) 

     Next i 

     FileListBox.DataSource = Subquery.ToList 

    Else 

     FileListBox.DataSource = query.ToList 

    End If 

感謝您的幫助, 安德魯

+0

我認爲[Predicate Builder](http://www.albahari.com/nutshell/predicatebuilder.aspx)是你正在尋找的! – Flowerking 2012-04-24 12:25:18

回答

0
Dim Channels = ChannelListBox.CheckedItems 
Dim ChannelNames = From c.ToString In Channels 
Dim query = From f As System.IO.FileInfo In StartList 
    Where f.Name.Contains("Romania") And ChannelNames.Any(Function(n) f.Name.Contains(n)) 

我沒有經驗VB.NET,更不用說使用LINQ,所以我希望我的語法是正確的。這裏是我會寫在C#中:

var channels = ChannelListBox.CheckedItems; 
var channelNames = channels.Select(c => c.ToString()); 
var query = from f in StartList.Cast<System.IO.FileInfo>() 
    where f.Name.Contains("Romania") && channelNames.Any(n => f.Name.Contains(n)) 
    select f; 
+0

還沒意識到我太無禮了,以至於不能謝謝你,所以我們現在遲了近三年:謝謝! – 2015-01-21 18:01:55

+0

不客氣! :-) – Andrew 2015-01-24 02:57:21