Based on a list of a typed class like
class CostCenter
{
string center;
string percentage;
DateTime start;
}
I have a list of these elements like this:
- {"a", 70, "2019/11/10"}
- {"b", 30, "2019/11/10"}
- {"A", 40, "2018/10/05"}
- {"B", 60, "2018/10/05"}
- {"xx", 10, "2010/01/01"}
- {"yy", 90, "2010/01/01"}
- {"100", 50, "2009/07/03"}
- {"101", 50, "2009/07/03"}
taking into account that I want to get rid of all of the elements (list
) that have a start date earlier or equal than a fixed(_earliestDate
), also this fixed data will replace the earliest match. In this example the earliest date is "2010/11/01", therefore "xx" and "yy" start date is replaced to "2010/11/01".
The output should be like this:
- {"a", 70, "2019/11/10"}
- {"b", 30, "2019/11/10"}
- {"A", 40, "2018/10/05"}
- {"B", 60, "2018/10/05"}
- {"xx", 10, "2010/11/01"}
- {"yy", 90, "2010/11/01"}
I have created the following code:
string dateToReplace = null;
bool earliestFound = false;
foreach (var item in list.OrderByDescending(x => DateTime.Parse(x.start)).ToList())
{
if (earliestFound) //already marked, safe to remove others
{
list.Remove(item);
continue;
}
if (!string.IsNullOrEmpty(dateToReplace)) //remaining matches
{
if (string.Equals(item.start, dateToReplace))
{
item.start = _earliestDate;
continue;
}
else
{
earliestFound = true;
list.Remove(item);
continue;
}
}
if (item.start <= _earliestDate) //first earliest or same, more required
{
dateToReplace = item.start;
item.start = _earliestDate;
}
}
dateToReplace
and earliestFound
will be used as flags in the code to determine when to loop.
Somehow I think it is not the best option, do you have any suggestion on how to make it easier to understand or efficient?