Home > Mobile >  Foreach with where clause when reading from a Sharepoint List
Foreach with where clause when reading from a Sharepoint List

Time:04-11

I am trying to filter a result set which I read from a Sharepoint(list). I have to filter records that have a user specified and sadly user column of the list is a lookup column and gets the actual username from another list.

Normally,I can get the username value of a record (if it has any) like this:

foreach (var item in listItems)
{
    if (item.FieldValues.TryGetValue("nqhs", out var userLookup))
    {
        if (userLookup != null && userLookup.ToString() == "Microsoft.SharePoint.Client.FieldUserValue")
        {
            var theUser = ((FieldLookupValue)item["nqhs"]).LookupValue; //this returns theUser = "John Doe"
        }
    }
}

nqhs is the name of the column which holds the Username in the Sharepoint list.

Is there any way I can apply this logic to a where clause in foreach, so that I can work with a much smaller result set?

I am trying something like this but I can't get it to work:

foreach (var item in listItems.Where(p => p.((FieldLookupValue)p["nqhs"]).LookupValue == "John Doe"))

Also tried this and get and "object reference not set to an instance of an object" error...

foreach (var item in from item in listItems where ((FieldLookupValue)item["nqhs"]).LookupValue == "John Doe" select item)

CodePudding user response:

Try filtering the lookup list first, and then use the filtered list in you foreach

var filteredList = listItems.Where(p => p.((FieldLookupValue)p["nqhs"]);

foreach(var item in filteredList)

Some queries to SP require an execution to return results before they can be used. It's also better for performance because the Where clause in your current loop will execute with each iteration.

  • Related