计算数组中的相邻日期

时间:2011-07-15 09:40:20

标签: c# arrays adjacency-list

我有一个大约1000条记录的数组,每条记录都是具有以下属性的对象:

- Result
    + Number: Integer (can repeat, not an ID)
    + Date: DateTime

我想计算并充分利用相邻日期的结果。
任何人都可以提出任何想法吗?

修改 例如:

I have an array:
List<Result> results = new List<Result> {
    new Result(){ Number = 34, Date = "7/15/2011" },
    new Result(){ Number = 59, Date = "7/15/2011" },
    new Result(){ Number = 11, Date = "7/15/2011" },

    new Result(){ Number = 1, Date = "7/16/2011" },
    new Result(){ Number = 3, Date = "7/16/2011" },
    new Result(){ Number = 34, Date = "7/16/2011" },

    new Result(){ Number = 98, Date = "7/17/2011" },
    new Result(){ Number = 34, Date = "7/17/2011" },
    new Result(){ Number = 29, Date = "7/17/2011" },
    new Result(){ Number = 99, Date = "7/17/2011" },
    new Result(){ Number = 1, Date = "7/17/2011" },

    new Result(){ Number = 31, Date = "7/18/2011" },
    new Result(){ Number = 76, Date = "7/18/2011" },
    new Result(){ Number = 47, Date = "7/18/2011" },
    new Result(){ Number = 34, Date = "7/18/2011" },

    new Result(){ Number = 99, Date = "7/19/2011" },
    new Result(){ Number = 0, Date = "7/19/2011" },
    new Result(){ Number = 88, Date = "7/19/2011" },
    new Result(){ Number = 33, Date = "7/19/2011" }
};

As you see, all i want is to get:
- Number = 34 with 4 adjacent days 
- Number = 1 with 2 adjacent days

2 个答案:

答案 0 :(得分:1)

var HighestAdjacentDate =
    Results.OrderByDescending(Result => 
        Results.Count(R => 
            Math.Abs((R.Date - Result.Date).Days) == 1)).FirstOrDefault();

答案 1 :(得分:0)

为简洁起见,假设有序输入

var sample = new [] {
    new { Number = 1, Date = DateTime.Now },
    new { Number = 2, Date = DateTime.Now.AddDays(5) },
    new { Number = 3, Date = DateTime.Now.AddDays(6) },
    new { Number = 4, Date = DateTime.Now.AddDays(9) }
};

var adjacent = sample
    .Where((o,i) => i>0 && (o.Date.Date - sample[i-1].Date.Date).Days<=1);

Console.WriteLine(string.Join("\n", adjacent));

对于此特定输入显示

H:\>csharp test.cs
{ Number = 3, Date = 7/21/2011 12:19:44 PM }