I have two lists and I need to sort a list with another list.
var orderList = new List<long>() {4, 55, 34};
var itemList = new List<Branch>() { {Id=55, Name="X"}, {Id=34, Name="Y"}, {Id=4, Name="Z"} };
How can I order second list namely itemList
according to first one orderList
?
Is there any linq short way?
Update:
orderList
will always have all expected Id
branch contained itemList
.
You could use LINQ
and order the items by their index in other array:
var orderedItemList = itemList.OrderBy(x => orderList.IndexOf(x.Id)).ToList();
you can perform below linq to solve your issue:
List<Branch> sortedProducts = new List<Branch>();
orderList.ForEach(x => sortedProducts.Add(itemList.FirstOrDefault(ele => ele.Id == x)));
Note:- here only those element will be added whose index is present in the orderList
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With