简体   繁体   中英

Order two different list of objects by date

I have 2 Lists each of different objects. Each list contains a date element. What I am trying to do is pull items from each list in sequence and do something.

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

I want to process these in order so i would do List 2 object 9/1, List 1 object 9/2, List 1 object 9/3, List 2 object 10/5

How can one achieve this?

How about this?

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

You now have a ordered list of type object. Which I can't see a way of getting around, So as you iterate through that list, you'll need to cast each object appropriately back by doing a switch and some pattern matching


Edit: for comepleteness here is the tuple version (I think its probably the best way to do it)

var newOrderedByDateCollection = list1
.Select(i => new Tuple<object,DateTime>(i, i.updateDate))
.Concat(list2
    .Select(j => new Tuple<object, DateTime>(j, j.updateDate)))
.OrderBy(tmp => tmp.Item2)
.Select(tmp => tmp.Item1);

If you want to keep type safety (avoid object ) and don't mind sorting the lists to new lists, you can do a loop with both indexes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM