我有一个文件夹系统,并且有一个规则,不允许您将多个文件夹添加到同一目录。添加文件夹时,我有以下逻辑。
// CHECK TO SEE IF FOLDER NAME ALREADY EXISTS
if (areaListViewIsVisible)
{
foreach (Folder folder in areaList)
{
if (pResult.Text == folder.Title)
{
await Application.Current.MainPage.DisplayAlert("Error", "You cannot add a folder with the same name.", "OK");
return;
}
}
}
else
{
if (productListViewVisible)
{
foreach (Folder item in productList)
{
if (pResult.Text == item.Title)
{
await Application.Current.MainPage.DisplayAlert("Error", "You cannot add a folder with the same name.", "OK");
return;
}
}
}
}
//
这似乎是一种不好的检查方法,您能推荐一种更好的方法吗?
谢谢!
答案 0 :(得分:1)
我想您可以使用LINQ的任何方法:
if(areaListViewIsVisible && areaList.Any(folder => folder.Title == pResult.Text))
{
await Application.Current.MainPage.DisplayAlert("Error", "You cannot add a folder with the same name.", "OK");
return;
}
答案 1 :(得分:1)
在这里,我添加了ToLower()
,以避免在比较names
时出现任何大小写问题。
if ((areaListViewIsVisible && areaList.Any(folder => folder.Title.ToLower() == pResult.Text.ToLower())||
(productListViewVisible && productListareaList.Any(folder => folder.Title.ToLower() == pResult.Text.ToLower()))
{
await Application.Current.MainPage.DisplayAlert("Error", "You cannot add a folder with the same name.", "OK");
return;
}