複数のデータを含む 2 つのリストボックスがあり、ListBox1 は次の形式です。
C:\Users\Charlie\Desktop\Trials\Trial0004COP.txt
そして私のListBox2で:
Trial0004COP
リストボックス 1 に Trial0004COP が存在するかどうかを確認するにはどうすればよいですか? Contain() を使用しましたが、機能しません。
次のようなものをお勧めします:
var searchString = "Trial0004COP";
var isFound = false;
foreach(var name in listbox1.items)
{
if (Path.GetFileNameWithoutExtension(name).ToLower() == searchString.ToLower())
{
_IsFound = true;
break;
}
}
Windows では、ファイル名の大文字と小文字は区別されませんが、大文字と小文字が区別されないため、大文字と小文字を無視してファイル名を確認する必要があります。
それがあなたのことなら、 Linqの1行でそれを行うことができます。
var searchString = "Trial0004COP";
var isFound = listBox1.Items.Cast<string>()
.Any(x => Path.GetFileNameWithoutExtension(x).ToLower() == searchString.ToLower());
What about:
bool found = listBox1.Items.Cast<string>()
.Where(x => x.Contains("Trial0004COP"))
.Any();
Or to make it more accurate use String.EndsWith()
method but you also have to add ".txt"
if you want to make it works:
bool found = listBox1.Items.Cast<string>()
.Where(x => x.EndsWith("Trial0004COP.txt"))
.Any();
Edit :
Hi Fuex, I'm using OpenFileDialog to select a file, then this file is added to my listbox1 with all the Directory name. In my listbox2 I read another file that contains several Trials000""" and add them to it, I want to know if the file that I selected from the open dialog exist in my listboz2
Yes can do it in this way:
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
}
LINQを使用すると、次のことができます。
listBox1.Items.Select(e => Path.GetFileNameWithoutExtension(e as string)).Contains("Trial0004COP");