# How to order list based on another list

•
•  |
•

### 문제

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 `ListT`using 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: 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: 도움이 되었습니까?

### 해결책

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();
}
``````
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow