1

enter image description here

Dear All,

My list constains date/time items and I want to get the biggest value of dates. For my example, 1 May 2012 nearest day for today? how can I compare these values and get latest one with C#? I accessed the list and Items in code;

using (SPWeb web = SPContext.Current.Site.RootWeb)
{
      SPList alertList = web.Lists["Alert Status"];
      if (alertList != null)
      {
          foreach (SPListItem alertItem in alertList.Items)
          {
              DateTime startDate = (DateTime)alertItem["Alert Date"];

          }
      }
} 
mkacar
  • 277
  • 1
  • 7
  • 17

2 Answers2

5

I recommend to retrieve and sort the items with a CAML query. You can use the SPQuery Class:

SPList list = web.Lists["Alert Status"];

SPQuery query = new SPQuery();
query.Query = @"<OrderBy><FieldRef Name='Alert_x0020_Date' Ascending='FALSE' /></OrderBy>";
query.RowLimit = 1;

SPListItemCollection items = list.GetItems(query);
return items.Count == 0 ? DateTime.MinValue : (DateTime) items[0]["Alert Date"];

If there are a lot items in your list, SPList.Items is very slow since all items are fetched from the database.

Update:

You should not dispose SPContext.Current.Site.RootWeb. It may be referenced later by other code. Use the rule only dispose objects you are opening yourself as guideline. See Disposing Objects for more information.

Stefan
  • 14,530
  • 4
  • 55
  • 62
  • +1 for explaining the right way of disposing SPWeb Object. Your answer would have been even better if you had suggested LINQ to SharePoint to OP. I can't think of going back to writing CAML string :-) – Ken May 01 '12 at 21:01
0

If you collect your dates like this:

List<DateTime> dates;
using (SPWeb web = SPContext.Current.Site.RootWeb)
{
  SPList alertList = web.Lists["Alert Status"];
  if (alertList != null)
  {
      dates = alertList.Items.Select(alertItem => (DateTime)alertItem["Alert Date"]).ToList();
  }
} 

This will give you the latest absolute date:

dates.OrderByDescending(date => date).First();

This will give you the date closest to right now:

dates.OrderBy(date => Math.Abs((date - DateTime.Now).TotalMilliseconds)).First();

yamen
  • 15,390
  • 3
  • 42
  • 52