我有两个不同对象的列表。每个列表都包含一个日期元素。我想要做的是按顺序从每个列表中提取项目并做一些事情。
Object1
{
string description
date updateDate
int value
}
Object2
{
string description
date updateDate
string descritpion2
}
IE
List<object1>
object1.date = 10/1/2017
object1.date = 9/3/2017
List<object2>
object2.date = 10/15/2017
object2.date = 9/1/2017
我想按顺序处理这些,所以我会做List 2对象9/1,List 1对象9/2,List 1对象9/3,List 2对象10/5
如何实现这一目标?
答案 0 :(得分:0)
这个怎么样?
[john,mike,tom]
您现在拥有了一个有序的对象列表。我无法找到一种方法,所以当您遍历该列表时,您需要通过切换和一些模式匹配来适当地回放每个对象
编辑:对于Comepleteness这里是元组版本(我认为它可能是最好的方法)
var list1 = new List<Object1>();
var list2 = new List<Object2>();
var newOrderedByDateCollection = list1
.Select(i => new TempClass(i, i.updateDate))
.Concat(list2
.Select(j => new TempClass(j, j.updateDate)))
.OrderBy(tmp => tmp.Date)
.Select(tmp => tmp.OrigItem);
//This could be replaced by a tuple like Tuple<object, DateTime> but I thought this would come across clearer
public class TempClass
{
public TempClass(object origItem, DateTime date)
{
OrigItem = origItem;
Date = date;
}
public object OrigItem { get; set; }
public DateTime Date { get; set; }
}
答案 1 :(得分:0)
如果您想保持类型安全(避免object
)并且不介意将列表排序到新列表,您可以使用这两个索引进行循环:
var l1count = l1.Count;
var l2count = l2.Count;
var ocount = l1count + l2count;
var l1o = l1.OrderBy(o => o.updateDate).ToList();
var l2o = l2.OrderBy(o => o.updateDate).ToList();
for (int j1 = 0, j2 = 0; j1 + j2 < ocount;) {
if (j1 < l1count && (l1o[j1].updateDate <= l2o[j2].updateDate || j2 >= l2count)) {
// process l1o[j1]
++j1;
}
else {
// process l2o[j2]
++j2;
}
}