开发者

Do I really need foreach loop for this?! (foreach probably overkilling)

开发者 https://www.devze.com 2023-01-29 18:32 出处:网络
I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem l开发者_Python百科i in list.items and loop through each item (if l

I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem l开发者_Python百科i in list.items and loop through each item (if li.name==myitemname then assign strguid=li.uniqueid.tostring()

Is there a way not to use foreach loop since I know the name of the item? This will save time to loop throught items.


If you are creating a spquery on your unique item in splistcollection you would be returned only one element which you can obtain without foreach


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


Works but I have 11 files and they all have the same file name "license.txt" and they are in the same document library. 1 file "license.txt" is under the root document library and other 10 in 10 different folders within a document library. so what if i am looking for the license.txt file that's in Demo folder?

This code works but only finds license.txt under the root. 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(); } } } }


Trying the following and it seems to be working.

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

or

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

精彩评论

暂无评论...
验证码 换一张
取 消