我有一个带有CheckedListBox的表单,用户可以在其中选择多个选项(它过滤目录文件列表 - 过滤后的文件出现在第二个列表框中)。
如果我有一定数量的选项,我可以在查询中使用“或”,如下所示:
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 :(得分: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;