开发者

Finding missing dates from a collection

I've dates array with values below: "07/07/2011开发者_如何学C", "08/05/2011", "09/07/2011", "12/07/2011"

Using this as input in my C# program, I need to build a new collection which will have missing dates..ie. 10/07/2011, 11/07/2011.

Is recursion the best way to achieve this?

Thanks.


Not at all. This should be a straightforward process. You have a starting date, you have an interval... You start walking the array and if the next value does not match your previous value plus the interval you insert a new value into the new array. If it does match, you copy that value.

If you need more data (metadata) about each entry then create a class that holds the date and whatever metadata you find useful (e.g. a bool like this_value_was_inserted_artificially)

Using recursion would unnecessarily complicate things.


No recursion needed. This can probably be optimized, but should do the job:

public static IEnumerable<DateTime> FindMissingDates(IEnumerable<DateTime> input)
{
    // get the range of dates to check
    DateTime from = input.Min();
    DateTime to = input.Max();

    // how many days?
    int numberOfDays = to.Subtract(from).Days;

    // create an IEnumerable<DateTime> for all dates in the range
    IEnumerable<DateTime> allDates = Enumerable.Range(0, numberOfDays)
        .Select(n => from.AddDays(n));

    // return all dates, except those found in the input
    return allDates.Except(input);
}


You can pull this off very nicely with Linq:

var dates=new[]{
    DateTime.Parse("07/07/2011"),
    DateTime.Parse("08/07/2011"),
    DateTime.Parse("09/07/2011"),
    DateTime.Parse("12/07/2011")};

var days=(dates.Max()-dates.Min()).Days;

var otherDays=
    Enumerable
        .Range(0,days)
        .Select(d=>dates.Min().AddDays(d))
        .Except(dates);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜