Compare two lists on razor and sort them by newest (both have created datetime)

299 Views Asked by At

I want to sort two models by Datetime, both of them going to one timeline so i need the newest from them to be on the start of the list timeline, I found solutions like Union models, but I want them to remain two separate lists..Is it possible?

foreach (var list1 in model.list1.OrderByDescending(a => a.created_datetime))
{
    09/18/19
}

foreach (var list2 in model.list2.OrderByDescending(a => a.created_datetime))
{
    09/19/19
}

Now I want the timeline result to be listed in the second list because it is an earlier result

2

There are 2 best solutions below

0
Daniel On BEST ANSWER

Thanks for your help, the most helpful solution I found to the problem is:- Sorting the list by a JS function that runs on the uploaded content.

here is the code:

var item = $(".sort-item").sort(function (a, b) {
                var Adate = $(a).attr("data-date");
                var Bdate = $(b).attr("data-date");
                var Atime = $(a).attr("data-time");
                var Btime = $(b).attr("data-time");
                if (Adate < Bdate) return 1;
                if (Adate > Bdate) return -1;
                if (Atime < Btime) return 1;
                if (Atime > Btime) return -1;
                return 0;
           });
           $(".timeline").prepend(item);
2
LeBoucher On

This is what you mean? (Using Linq)

var merged = list1.Union(list2).OrderByDescending(d => d.Date);

Note that this is only possible, when the two lists are the same type. Other note, that this returns an IEnumerable, not a new List, so every time you enumerate it, the merge will be calculated. You have to call ToList() at the end if you want to create a new List to prevent this, but this can be very suboptimal in performance if you have large lists.

Example program:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Lists
{
    class Program
    {
        static void Main(string[] args)
        {
            var list1 = new List<DateItem>
            {
                new DateItem{Date = DateTime.UtcNow.AddDays(-2), Name = "The day before yesterday" },
                new DateItem{Date = DateTime.UtcNow.AddDays(1), Name = "Tomorrow" }
            };

            var list2 = new List<DateItem>
            {
                new DateItem{Date = DateTime.UtcNow.AddDays(2), Name = "The day after tomorrow" },
                new DateItem{Date = DateTime.UtcNow.AddDays(-1), Name = "Yesterday" },
                new DateItem{Date = DateTime.UtcNow, Name = "Today" }
        };

            var merged = list1.Union(list2).OrderByDescending(d => d.Date);

            foreach (var day in merged)
            {
                Console.WriteLine(day.Name);
            }
        }
    }

    class DateItem
    {
        public DateTime Date { get; set; }
        public string Name { get; set; }
    }

}