In many programming scenarios, you may find yourself with two lists: one containing identifiers and another containing items associated with those identifiers. The challenge arises when you need to maintain the same order of items in both lists. This article provides a simple and efficient solution using LINQ to address this problem.
Suppose you have a list of identifiers:
List<long> docIds = new List<long>() { 6, 1, 4, 7, 2 };
You also have a list of items represented by the IDs in docIds:
List<T> docs = GetDocsFromDb(...);
Your goal is to rearrange the docs list in ascending order based on the corresponding identifiers in docIds. The order of items in both lists should be identical.
The following LINQ expression solves this problem:
docs = docs.OrderBy(d => docIds.IndexOf(d.Id)).ToList();
Explanation:
This method efficiently reorders the docs list based on the identifiers in docIds, ensuring that the items in both lists are in the same order.
The above is the detailed content of How to Sort a List Based on the Order of Identifiers in Another List Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!