【问题标题】:Whats a nicer way of searching a list for a specific property [closed]什么是搜索特定属性列表的更好方法[关闭]
【发布时间】:2018-06-26 08:13:06
【问题描述】:

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

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

这似乎是一种不好的检查方式,您能推荐一种更好的方式吗?

谢谢!

【问题讨论】:

  • 为新文件夹创建路径并检查该路径是否已存在。参考this
  • 这个问题更像是一个代码审查请求,而不是一个中肯的问题描述。这不属于这里,也许它属于 Code Review。
  • 只是将foreach循环重构为单独的检查函数?

标签: c# list linq


【解决方案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;
}

【讨论】:

  • 感谢您的回答,使用 Alex 的解决方案有两个 if 语句或像您所做的那样在一个 if 语句中查询两个 if 语句更有效?
  • @SeanDavies 完全取决于您的代码结构,如果您必须为产品和区域执行不同的任务,那么您需要有两个不同的if 条件,否则如果两者都有相同的任务(如你问过)那么就没有必要有两个if条件。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多