【问题标题】:Do I really need foreach loop for this?! (foreach probably overkilling)我真的需要 foreach 循环吗?! (foreach 可能矫枉过正)
【发布时间】:2010-12-15 02:08:37
【问题描述】:

我需要获取项目的 GUID。我知道 SiteURL、列表名称和项目名称。如何在 list.items 中使用 splistitem li 并循环遍历每个项目(如果 li.name==myitemname 然后分配 strguid=li.uniqueid.tostring()

有没有办法不使用 foreach 循环,因为我知道项目的名称?这将节省循环遍历项目的时间。

【问题讨论】:

  • SPList.GetItems(SPQuery)。我想我需要构建我的查询。但它使用了 listcollection ,所以再次尝试一切......嗯
  • 姓名?你是说标题吗?

标签: sharepoint loops foreach


【解决方案1】:

如果您在 splistcollection 中为您的唯一项目创建一个 spquery,您将只返回一个元素,您可以在没有 foreach 的情况下获得该元素

【讨论】:

    【解决方案2】:
     using (SPSite site = new SPSite(SiteURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList apps = web.GetList(web.Url + "/Lists/MyList");
                        SPQuery query = new SPQuery();
                        query.Query = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='String'>{0}</Value></Eq></Where>", _title);
                        items = apps.GetItems(query);
                        if(items.Count > 0)
                           {
                             Guid id = items[0].UniqueId;
                           }
                    }
                }
    

    【讨论】:

    • qry.ViewAttributes = "Scope='RecursiveAll'";或 query.ViewAttributes = "Scope=\"Recursive\"";
    【解决方案3】:

    有效,但我有 11 个文件,它们都具有相同的文件名“license.txt”,并且它们位于同一个文档库中。 1 个文件“license.txt”位于根文档库下,其他 10 个位于文档库中的 10 个不同文件夹中。那么如果我正在寻找 Demo 文件夹中的 license.txt 文件呢?

    此代码有效,但只能在根目录下找到 license.txt。 private void btnGetFileGuid_Click(object sender, EventArgs e) { using (SPSite site = new SPSite("https://www.abc.com/sites/Software")) { using (SPWeb web = site.OpenWeb()) { SPList spList = web.Lists["Auto Cad"]; string fileName = "license.txt"; SPQuery query = new SPQuery(); query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>"; SPListItemCollection items = spList.GetItems(query); if (items.Count > 0) { Guid id = items[0].UniqueId; lblGuid.Text = id.ToString(); } } } }

    【讨论】:

    • 有人能解决这个问题吗?我在同一个文档库的不同文件夹中有 10 多个项目。它没有找到任何一个。我认为它只有在项目位于 doc lib 的根目录中并且只计算这一项时才有效。
    【解决方案4】:

    尝试以下,它似乎工作。

    query.ViewAttributes = "Scope=\"Recursive\""; 
    

    query.ViewAttributes = "Scope='RecursiveAll'"; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多