0

我有两个包含多个数据的列表框,ListBox1 具有以下格式:

C:\Users\Charlie\Desktop\Trials\Trial0004COP.txt

在我的 ListBox2 中:

Trial0004COP

如何检查我的 listbox1 中是否存在 Trial0004COP?我使用了 Contain() 但它不起作用。

4

3 回答 3

1

我会推荐类似的东西:

var searchString = "Trial0004COP";
var isFound = false;
foreach(var name in listbox1.items)
{
    if (Path.GetFileNameWithoutExtension(name).ToLower() == searchString.ToLower())
    {
        _IsFound = true;
        break;
    }
}

请注意,在 Windows 中,文件名保留大小写但不区分大小写,因此您需要检查文件名而忽略其大小写。

如果这是你的事,你可以在Linq的一行中完成。

var searchString = "Trial0004COP";
var isFound = listBox1.Items.Cast<string>()
                            .Any(x => Path.GetFileNameWithoutExtension(x).ToLower() == searchString.ToLower());
于 2012-09-19T16:36:14.953 回答
0

关于什么:

bool found = listBox1.Items.Cast<string>()
                           .Where(x => x.Contains("Trial0004COP"))
                           .Any();

或者让它更准确的使用方法,但如果你想让它工作,String.EndsWith()你还必须添加:".txt"

bool found = listBox1.Items.Cast<string>()
                           .Where(x => x.EndsWith("Trial0004COP.txt"))
                           .Any();

编辑 :

嗨 Fuex,我正在使用 OpenFileDialog 选择一个文件,然后将该文件与所有目录名称一起添加到我的 listbox1 中。在我的 listbox2 中,我读取了另一个包含多个 Trials000""" 的文件并将它们添加到其中,我想知道我从打开对话框中选择的文件是否存在于我的 listboz2

是的可以这样做:

bool found = false;
if(openFileDialog.ShowDialog() == DialogResult.OK){
   found = listBox.Items.Cast<string>()
                        .Where(x => x.EndsWith(openFileDialog.FileName))
                        .Any();

   if(!found)
      MessageBox.Show(openFileDialog.FileName + " doesn't exist in listBox1"); //show a message
}
于 2012-09-19T16:25:22.017 回答
0

使用LINQ,您可以:

listBox1.Items.Select(e => Path.GetFileNameWithoutExtension(e as string)).Contains("Trial0004COP");
于 2012-09-19T18:09:45.947 回答