基于属性拆分对象列表

本文关键字:拆分 对象 列表 属性 于属性 | 更新日期: 2023-09-27 17:49:26

myClass结构:

public class myClass
    {
        public string Name { get; set; }
        public string AdditionalData { get; set; }
        public System.DateTime ActivityTime { get; set; }
    }

我有一个以上类List<myClass>的列表,它们都是按ActivityTime排序的。

我需要分割上述列表并获得List<List<myClass>>,这样,如果两个连续的ActivityTime之间存在超过特定时间段的差异,例如5分钟,我希望进行分割。

任何帮助都是真诚的感谢。

谢谢

基于属性拆分对象列表

您可以在一个简单的迭代中做到这一点:

var myList = new List<myClass>()
{
    new myClass() { Name = "ABC", AdditionalData = "1", ActivityTime = DateTime.Now },
    new myClass() { Name = "ABC2", AdditionalData = "2", ActivityTime = DateTime.Now },
    new myClass() { Name = "ABC3", AdditionalData = "3", ActivityTime = DateTime.Now.AddSeconds(6) },
    new myClass() { Name = "ABC4", AdditionalData = "3", ActivityTime = DateTime.Now.AddSeconds(11) },
    new myClass() { Name = "ABC4", AdditionalData = "3", ActivityTime = DateTime.Now.AddSeconds(12) }
};
var results = new List<List<myClass>>();
myClass previousItem = null;
List<myClass> currentList = new List<myClass>();
foreach (var item in myList)
{
    if (previousItem == null || (item.ActivityTime - previousItem.ActivityTime).TotalSeconds >= 5)
    {
        currentList = new List<myClass>();
        results.Add(currentList);
    }
    currentList.Add(item);
    previousItem = item;
}

这个解决方案如何:

var data = new List<myClass> {
    new myClass { ActivityTime = new DateTime(2016, 01, 01, 01, 00, 00) },
    new myClass { ActivityTime = new DateTime(2016, 01, 01, 01, 05, 00) },
    new myClass { ActivityTime = new DateTime(2016, 01, 01, 01, 06, 00) },
    new myClass { ActivityTime = new DateTime(2016, 01, 01, 01, 07, 00) },
    new myClass { ActivityTime = new DateTime(2016, 01, 01, 01, 17, 00) }
};
var period = 5;
var firstActivityTime = data.Min(x => x.ActivityTime);
var answer = data.OrderBy(x => x.ActivityTime).GroupBy(x => {
        var dif = (x.ActivityTime - firstActivityTime).Minutes;
        return dif / period - (dif % period == 0 && dif / period != 0 ? 1 : 0);
    }).Select(x => x.ToList()).ToList();

实现这一目标的方法多种多样,但基本原理是相同的。处理n(th)元素时,跟踪n-1 (th)元素,计算两者之间的timespan

你可以这样做。

List<MyClass> data = ...; // input
int gid=0;
DateTime prevvalue = data[0].ActivityTime;                          // Initial value 
var result =  data.Select(x=>
{
    var obj =  x.ActivityTime.Subtract(prevvalue).TotalMinutes<5?  // Look for timespan difference
                 new {gid= gid, item =x}                          // Create groups based on consecutive gaps. 
                :new {gid= ++gid, item =x};
    prevvalue= x.ActivityTime;                                      // Keep track of previous value (for next element process)
    return obj;
})
.GroupBy(x=>x.gid)                                                  // Split into groups 
.Select(x=>x.Select(s=>s.item).ToList())
.ToList();

检查Demo