I have a list List<T> ListT of custom object type<T>.

Now there are two items in the list, one with ID = 1089 and another with ID = 1090

Based on some logic, I will sort ListTusing following way:

ListT = ListT.OrderByDescending(x=>x.Order.HasValue).ThenBy(x=>x.Order).ToList();

After the above query, ListT will now have ID = 1090 be the first item and ID = 1089 as second item.

Now I will retrieve another new list, ListB from database. The sample data would be as below:

enter image description here

My objective is to rearrange ListB so that the order of ID in ListB following the order of ID in ListT, and after that, rearrange ListB so that it would following the Order value in ascending order.

In the end, the expected result should be:

enter image description here

Was it helpful?


Something like this perhaps:

public class Foo {
    public int ID { get; set; }
    public int? Order { get; set; }

    public Foo(int id, int? order) {
        ID = id;
        Order = order;

static void Main(string[] args) {

    var ListT = new List<int> {1090,1089};
    var ListTOrder = ListT.Select((x, index) => new { Item = x, Index = index }).ToDictionary(x => x.Item, x => x.Index);

    List<Foo> ListB = new List<Foo> {
        new Foo(1089, 1),
        new Foo(1089, 3),
        new Foo(1089, 4),
        new Foo(1089, null),                
        new Foo(1090, 1),
        new Foo(1090, 3),
        new Foo(1090, 4)

    ListB = ListB.OrderBy(x => ListTOrder[x.ID]).ThenBy(x => x.Order).ToList();


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top