根据属性c#拆分对象列表

时间:2016-06-27 06:17:37

标签: c#

myClass结构:

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

我有一个按活动时间排序的上述类List<myClass>的列表。

我需要拆分上面的列表并得到一个List<List<myClass>>,如果两个连续的ActivityTime之间存在超过一个特定时期的差异,那么我希望进行拆分。

真心感谢任何帮助。

由于

3 个答案:

答案 0 :(得分:3)

这个solution怎么样:

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();

答案 1 :(得分:3)

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

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;
}

答案 2 :(得分:2)

这可以实现各种方法,但基本原理是相同的。处理n-1元素时跟踪n(th)(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