Search code examples
c#linqcaml

Linq Where statement is not considering times


I want to grab all items from a list in SharePoint, except for a very specific situation. Currently, I am grabbing everything with CAML Query, then removing them from list using LINQ WHERE statement. The Suspense field is a date being pulled from SharePoint (Basically an expiration date), and the Closure is a simple Text field that users add closing information to. If the suspense date/time is before the current date/time, and closure field has no input(null), I want them to be exluded from my query.

I couldn't get the results I want using pure CAML query, so I grabbed everything and then tried to filter it using LINQ after. CAML Query:

<View><Query><OrderBy><FieldRef Name='Suspense' /></OrderBy></Query></View>

LINQ (What I want to do in CAML Query):

.Where(x => !(x.Suspense < DateTime.Now && x.Closure != null)) I want to select all from sp-list where !(Suspense date is before the current date && Closure is not null)

My linq query is not taking the time into consideration, only the date. If I run the query, while having a task that with a suspense date of today, but a time from earlier today, it still shows in my results.

Full code block (My XML Is being stripped out.. but you can see the query above):

// get action items

var query = new CamlQuery() { ViewXml = "<View><Query><OrderBy><FieldRef Name='Suspense' /></OrderBy></Query></View>" };
var actionItems = actionsList.GetItems(query);
context.Load(actionItems);
context.ExecuteQuery();
actions = actionItems.AsEnumerable()
            .Select(x => new Models.Action()
            {
              Id = x.Id,
              ItemNum = ListItemExt.GetInt32(x, "ID"),
              WhoLead = ListItemExt.GetUser(x, "Who_x0020_L_x002d_Lead"),
              WhoSupport = ListItemExt.GetUser(x, "Who_x0020_S_x002d_Spt"),
              What = ListItemExt.GetString(x, "Title"),
              Suspense = ListItemExt.GetDateTime(x, "Suspense"),
              Closure = ListItemExt.GetString(x, "Closure")
            }).Where(x => !(x.Suspense < DateTime.Now && x.Closure != null)).ToList();
    lastModified = actionsList.LastItemModifiedDate;
}

return Json(new { Actions = actions, LastModified = lastModified}, JsonRequestBehavior.AllowGet);

EDIT: I have found that my Suspense date is coming from Sharepoint in UTC Format, while my c# DateTime.Now is local. Could this cause the issue?


Solution

  • Sharepoint CSOM fields come over as UTC. I was using DateTime.Now, switching to DateTime.UtcNow fixed my issue. Thank you @Henk