非 Linq 答案
给定
public enum JobTypes
{
JobType1,
JobType2,
JobType3
}
public class Job
{
public JobTypes JobType { get; set; }
public DateTime CreatedOn { get; set; }
}
public class JobSummary
{
public JobSummary(JobTypes jobType, long count)
{
this.JobType = jobType;
this.Count = count;
}
public JobTypes JobType { get; set; }
public long Count { get; set; }
}
那么你可以
private List<JobSummary> GetOrderedSummary(List<Job> collection)
{
var result = new List<JobSummary>();
if (!collection.Any())
{
return result;
}
var orderedCollection = collection.OrderBy(j => j.CreatedOn);
var temp = orderedCollection.First();
var count = 1;
foreach (var job in orderedCollection.Skip(1))
{
if (temp.JobType == job.JobType)
{
count++;
continue;
}
result.Add(new JobSummary(temp.JobType, count));
temp = job;
count = 1;
}
result.Add(new JobSummary(temp.JobType, count));
return result;
}
使用
private void DoSomething()
{
var collection = new List<Job>
{
new Job{JobType = JobTypes.JobType1, CreatedOn = DateTime.Now},
new Job{JobType = JobTypes.JobType2, CreatedOn = DateTime.Now.AddSeconds(1)},
new Job{JobType = JobTypes.JobType2, CreatedOn = DateTime.Now.AddSeconds(2)},
new Job{JobType = JobTypes.JobType2, CreatedOn = DateTime.Now.AddSeconds(3)},
new Job{JobType = JobTypes.JobType2, CreatedOn = DateTime.Now.AddSeconds(4)},
new Job{JobType = JobTypes.JobType3, CreatedOn = DateTime.Now.AddSeconds(5)},
new Job{JobType = JobTypes.JobType3, CreatedOn = DateTime.Now.AddSeconds(6)},
new Job{JobType = JobTypes.JobType1, CreatedOn = DateTime.Now.AddSeconds(7)},
new Job{JobType = JobTypes.JobType1, CreatedOn = DateTime.Now.AddSeconds(8)},
};
var summary = GetOrderedSummary(collection);
}