在C#

时间:2019-06-25 10:10:32

标签: c# sharepoint

我需要帮助以我的C#代码获取SharePoint lookupvalue

使用Microsoft.SharePoint.Client;

public static ListItemCollection GetData(string SharePointSiteURL, string 
Table, string Query)
    {

        ClientContext Connection = new ClientContext(SharePointSiteURL);
        Connection.Credentials = 
System.Net.CredentialCache.DefaultNetworkCredentials;
        Connection.RequestTimeout = 3000000;

        CamlQuery QueryObject = new CamlQuery();
        QueryObject.ViewXml = Query;

        Web Web = Connection.Web;
        List List = Web.Lists.GetByTitle(Table);
        ListItemCollection ListItemCollection = List.GetItems(QueryObject);
        Connection.Load(ListItemCollection);
        Connection.ExecuteQuery();
        return ListItemCollection;

    }            



string SharePointSiteURL = "SiteURLHidden"
string Table = "Config - Clients";
        string Query = @"<View><Query><Where><IsNotNull><FieldRef Name = 'Title'/></IsNotNull></Where></Query><RowLimit>10000</RowLimit></View>";

        ListItemCollection listItemCollection = GetData(SharePointSiteURL, Table, Query);

        BindableCollection<ClientModel> _allClients = new BindableCollection<ClientModel>();


        foreach (ListItem listItem in listItemCollection)
        {

_allClients.Add(new ClientModel
            {
                Client = listItem["Title"].ToString(), //This works fine because its just a string.
                PrimaryMethod = (listItem["PrimaryMethod"] as FieldLookupValue).LookupValue //this doesn't as it throws null value exceptions and also this is a multi value lookup field and i have no idea how to handle this in c# code. say i want each value in this as a Collection as well.

}


}

因此只需从多值字段中提取字符串,然后将其作为集合返回即可,如果为null,则不会出错。我在任何地方都找不到有关如何执行此操作的信息,我知道它的工作原理与PowerShell中的代码相同,但是它可以正常工作,因为PowerShell不在乎类型haha

2 个答案:

答案 0 :(得分:1)

由于它是一个多查找列,因此您必须使用此方法来获取查找值:

var items = listItem["PrimaryMethod"] as FieldLookupValue[];
foreach (var x in items)
{
     //x.LookupValue;
}

答案 1 :(得分:1)

对于多个查询值,需要构建一个FieldLookupvalue集合,然后循环该集合以获取多个查询值:

    var PrimaryMethod = (FieldLookupValue[])listItem["PrimaryMethod"];
    foreach (FieldLookupValue lookupValue in PrimaryMethod)
    {
      Console.WriteLine(lookupValue.LookupValue);
    }