Home >Backend Development >C++ >How Can I Sort a List Based on the Order of IDs in Another List Using LINQ?
Sorting a List Based on IDs from Another List Using LINQ
In software development, it is often necessary to work with multiple lists that have corresponding elements. In this case, the user has two lists: one containing a series of identifiers (docIds) and another containing corresponding T items (docs). The challenge is to sort the docs list in the same order as the docIds list, while maintaining the original type of the docs list (List
To achieve this using LINQ (Language Integrated Query), one can utilize the OrderBy extension method. This method takes a lambda expression that specifies how the elements in the collection should be ordered. In this specific case, the lambda expression needs to access the Id property of each item in the docs list to compare it with the corresponding identifier in the docIds list.
The following LINQ expression accomplishes this task:
docs = docs.OrderBy(d => docIds.IndexOf(d.Id)).ToList();
This expression will iterate over the docs list, for each item, it will call the IndexOf method on the docIds list to determine the position of the corresponding identifier. The result is an ordered enumerable, which is then assigned to the docs list. By using the ToList method, the ordered enumerable is converted back to a List
In summary, this LINQ expression provides a simple and efficient way to reorder a list of items based on identifiers from another list, allowing for the preservation of both the order and type of the original list.
The above is the detailed content of How Can I Sort a List Based on the Order of IDs in Another List Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!