C# 搜索特定属性列表的更好方法是什么

C# 搜索特定属性列表的更好方法是什么,c#,list,linq,C#,List,Linq,我有一个文件夹系统,有一个规则,你不允许添加多个文件夹到同一个目录。添加文件夹时,我有以下逻辑 // CHECK TO SEE IF FOLDER NAME ALREADY EXISTS if (areaListViewIsVisible) { foreach (Folder folder in areaList) { if (pResult.Text == folder.Title) { await Applicatio

我有一个文件夹系统,有一个规则,你不允许添加多个文件夹到同一个目录。添加文件夹时,我有以下逻辑

// 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;
            }
        }
    }
}
//
这似乎是一种不好的检查方法,你能推荐一种更好的方法吗


谢谢

我想您可以使用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;
}

我想您可以使用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;
}

在这里,我添加了
ToLower()
,以避免在比较
名称时出现任何案例问题

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;
}

在这里,我添加了
ToLower()
,以避免在比较
名称时出现任何案例问题

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;
}

为新文件夹创建路径,并检查该路径是否已存在。提到这个问题更多的是一个代码审查请求,而不是一个直截了当的问题描述。这不属于这里,可能是在代码检查时。只需将foreach循环重构为一个单独的检查函数?为新文件夹创建一个路径,并检查该路径是否已经存在。提到这个问题更多的是一个代码审查请求,而不是一个直截了当的问题描述。这不属于这里,可能是在代码审查时。只需将foreach循环重构为一个单独的检查函数?感谢您的回答,这更有效,使用Alex的解决方案使用两个if语句,或者像您这样在一个if语句中查询两个if语句?@SeanDavies这完全取决于您的代码结构,如果您必须为产品和区域执行不同的任务,那么您需要有两个不同的
if
条件,否则如果两者都有相同的任务(如您所要求的),那么就不需要有两个
if
条件。感谢您的回答,这样效率更高,要使用Alex的解决方案创建两个if语句,或者像您这样在一个if语句中同时查询两个if语句?@SeanDavies这完全取决于您的代码结构,如果您必须为产品和区域执行不同的任务,那么您需要有两个不同的
if
条件,否则如果两者都有相同的任务(如您所要求的)那么就不需要有两个
if
条件。