5

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.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
ahmet
  • 702
  • 1
  • 10
  • 29
  • What should happen to items from `itemList` that doesn't exist in `orderList` ? How should they be ordered in this scenario? – Fabjan Jun 12 '18 at 08:05
  • @Fabjan, there is not such a case in my problem. I get itemList according to orderList. If you have a solution to get itemList ordered by orderList then it is also accepted – ahmet Jun 12 '18 at 08:06
  • 1
    @Fabjan I didn't see the comment of the OP so I updated his question. – CodeNotFound Jun 12 '18 at 08:20

4 Answers4

4

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

var orderedItemList = itemList.OrderBy(x => orderList.IndexOf(x.Id)).ToList();
Fabjan
  • 13,506
  • 4
  • 25
  • 52
4

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.

Lucifer
  • 1,594
  • 2
  • 18
  • 32
2

You can do the following:

itemList = itemList.OrderBy(d => orderList.IndexOf(d.Id)).ToList();
Raviraj Palvankar
  • 879
  • 1
  • 5
  • 9
2

you can order by the index of the Id in the orderList:

var result = itemList.OrderBy(e => orderList.IndexOf(e.Id)).ToList();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126