kamalpreet kamalpreet - 3 months ago 10
C# Question

Setting EndDate based on StartDate in next list item in a C# List

I have a C# list items as follows-

List<MyClass> All_Items = GetListItems();


GetListItems()
returns the result as follows-

Category StartDate EndDate
AA 2008-05-1
AA 2012-02-1
BB 2009-09-1
BB 2010-08-1
CC 2009-10-1


Using LINQ on
All_Items
, I want to update EndDate column in a way that if


  1. If the current Category's StartDate is less than the Start Date of next bigger date item within same Category then use one less day than that of bigger date.

  2. If there is no bigger date remaining then update to 2099-12-31



Final result is as follows-

Category StartDate EndDate
AA 2008-05-1 2012-01-31
AA 2012-02-1 2099-12-31
BB 2009-09-1 2010-07-31
BB 2010-08-1 2099-12-31
CC 2009-10-1 2099-12-31


I can only think of getting it done using too many loops. What is the better option?

Answer

Try this code. It Loops over all items and selects the next bigger item.StartDate for the same category. If such an item is not available it sets you default date.

I couldn't Test thecode as I'm writing on my mobile, so any correction is welcome.

foreach(var item in All_Items)
{
    var nextItem = (from i in All_Items 
                          where i != null && 
                                      i.Category==item.Category &&
                                      i.StartDate > item.StartDate
                          order by i.StartDate
                          select i).FirstOrDefault();
   Item.EndDate= nextItem!=null?nextItem.StartDate.AddDays(-1):new DateTime(2099,12,31);
}
Comments