我正在使用此代码在目录中搜索具有某些参数的文件,尽管其中一些可以留空,因此' ||'在代码中。我们正在使用Linq函数。
private void btnSearch_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"c:\Work\TestDirectory");
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
string stringSearch = string.Empty;
//string stringSearch = "test";
DateTime? dateSearch = null;
//DateTime? dateSearch = new DateTime(2016, 1, 1);
string fileType = string.Empty;
//string fileType = ".txt";
IEnumerable<System.IO.FileInfo>
fileQuery =
from file in fileList
where (
//Search value for name is NULL or FileName contains the search string
(string.IsNullOrEmpty(stringSearch) || file.Name.Contains(stringSearch))
//AND Search date is null or File Last Access time was before search date
&& ((!dateSearch.HasValue) || file.LastAccessTime < dateSearch.Value)
//AND Search file type is null or File extension = search type
&& (string.IsNullOrEmpty(fileType) || file.Extension.Equals(fileType))
//Modified before
&& ((!dateSearch.HasValue) || file.LastWriteTime < dateSearch.Value)
//Modified After
&& ((!dateSearch.HasValue) || file.LastWriteTime > dateSearch.Value)
//etc
)
orderby file.Name
select file;
//Execute the query.
foreach (System.IO.FileInfo fi in fileQuery) ;
{
listBox1.Items.Add(fileList);
}
}
}
}
当我点击我的搜索按钮时,我得到&#34; fileInfo [] array&#34;在我的列表框中。任何人都可以帮我解释为什么会这样? 感谢
答案 0 :(得分:0)
使用.Add()
添加单个项目
listbox1.Items.Add(fi);
或使用.AddRange()
添加项目列表
listBox1.Items.AddRange(fileQuery.ToList());
请参阅msdn链接以获取更多信息MSDN