I have a list of events in C# webpages, which includes the properties
- date (
DateTime
) - and description (
string
).
I want to sort this list by date, using LINQ, however I want to do this with the next closest date (to the current date) first in the list and the one furthest away last.
So for example, if the date was 1st on Jan, the first in the list would be 1st Jan, and last in the list would be 31st December.
Day and month are relevant, but year isn't.
I have researched this, but I am not really sure where to start.
Any help would be much appreciated.
Thanks for the all the answers and sorry my question was vague. I was trying to produce a list of events on dates, with the nearest dates at the top of the list - for example a list of birthdays - with the next upcoming birthday at the top, and the last upcoming birthday at the end. I'm sure my code can be taken apart, as I am by no means a professional - but this does what I need it to.
this was how I answered it in the end:
I created a class for events:
public class Events
{
public int ContactId { get; set; }
public string Lastname { get; set; }
public string Firstname { get; set; }
public DateTime EventDate { get; set; }
public string Description { get; set; }
public DateTime Now { get; set; }
public bool Reminder { get; set; }
public TimeSpan Difference { get; set; }
public int SortValue { get; set; }
public Events(int contactId, DateTime date, string lastname, string firstname, string description, bool reminder)
{
ContactId = contactId;
EventDate = date;
Description = description;
Reminder = reminder;
Now = DateTime.Now;
Lastname = lastname;
Firstname = firstname;
Difference = EventDate - Now;
SortValue = Convert.ToInt32(Difference.Days % 365);
if (SortValue < 0) { SortValue += 365; }
}
}
I then used the following in my code:
var upcomingEvents = new List<Events>();
foreach (var eventt in db.Query("SELECT CONTACT_ID, LASTNAME, FIRSTNAME, DATE, DESCRIPTION, REMINDER FROM CONTACTS INNER JOIN EVENTS ON CONTACTS.ID = EVENTS.CONTACT_ID WHERE CONTACTS.CUSTOMER_ID = @0", WebSecurity.CurrentUserId)){
var newEvent = new Events(eventt.CONTACT_ID, eventt.DATE, eventt.LASTNAME, eventt.FIRSTNAME, eventt.DESCRIPTION, eventt.REMINDER);
upcomingEvents.Add(newEvent);
}
upcomingEvents = upcomingEvents.OrderBy(x => x.SortValue).ThenBy(x=>x.Lastname).ToList();