什么是最好的循环使用?

时间:2015-10-07 22:21:04

标签: c# foreach ms-word

我正在制作一个与我们的EDRMS软件集成的Microsoft Word插件。

在这个插件上,有一个按钮可以创建一个新的Word文档并将其保存到EDRMS中。

但是,当打开现有文档时,此按钮也可用。

我希望能够添加某种验证,以便在用户点击现有文档上的“新建”按钮时,会出现一个消息框,指出该文档已存在。

我一直在使用foreach循环,因为它在第一个结果停止时效果不佳。

我可以使用的最佳循环是先完成所有结果然后确定文档是否存在或是否可以创建新文档。

我的代码如下:

    private void btnNewDoc_Click(object sender, EventArgs e)
    {
        try
        {
            string docName = Globals.ThisAddIn.Application.ActiveDocument.Name;

            string res = Path.GetFileNameWithoutExtension(docName);

            string fileloc = Path.GetFullPath(docName);

            //searches through all existing documents that are checked out to me
            TrimMainObjectSearch recser = new TrimMainObjectSearch(db, BaseObjectTypes.Record);
            recser.SetSearchString("checkedOutBy:me");

            foreach (Record resultRecord in recser)
            {
                //if the document doesnt appear in the checked out results, then create the new document
                if (res != resultRecord.Title)
                {
                    //code to create the new doc
                }
                //otherwise display a message
                else
                {
                    MessageBox.Show("This is an existing document - " + resultRecord.Number.ToString());
                }
            }

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

1 个答案:

答案 0 :(得分:1)

在你的循环中

foreach (Record resultRecord in recser)
{
    //if the document doesnt appear in the checked out results, then create the new document
    if (res != resultRecord.Title)
    {
        //code to create the new doc
    }
    //otherwise display a message
    else
    {
        MessageBox.Show("This is an existing document - " + resultRecord.Number.ToString());
    }
}

如果第一个结果与res不同,则创建一个新文档。那不是你想要的行为。目前还不清楚你是否在这一点上突破了循环,因为你还没有显示代码细节。

bool foundExistingTitle = false;
foreach (Record resultRecord in recser)
{

    //if the document doesnt appear in the checked out results, then create the new document
    if (res == resultRecord.Title)
    {
        foundExistingTitle = true;
        break;
    }
}

if (foundExistingTitle)
{
    MessageBox.Show("This is an existing document - " + resultRecord.Number.ToString());
}

}

如果您想使用Linq,可以大大简化该代码。

bool foundExistingTitle = resultRecord.Where(r => r.Title == res).Any();