Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq Order a list with a reference list [duplicate]

Tags:

c#

linq

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.

like image 547
ahmet Avatar asked Jun 12 '18 08:06

ahmet


2 Answers

You could use LINQ and order the items by their index in other array:

var orderedItemList = itemList.OrderBy(x => orderList.IndexOf(x.Id)).ToList();
like image 149
Fabjan Avatar answered Nov 09 '22 22:11

Fabjan


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.

like image 28
Lucifer Avatar answered Nov 09 '22 23:11

Lucifer