Home >Backend Development >C++ >How to Sort a List of Objects Based on IDs from a Separate List?

How to Sort a List of Objects Based on IDs from a Separate List?

DDD
DDDOriginal
2025-01-19 12:16:09981browse

How to Sort a List of Objects Based on IDs from a Separate List?

Sort a list of objects based on an ID in another list

In some cases you may need to sort a list of objects based on their IDs stored in a separate list. Consider the following:

You have a docIds named List<long> with the following values: { 6, 1, 4, 7, 2 }. Additionally, you have a docs named List<T> that stores the object represented by the ID in the docIds.

Your goal is to maintain consistency in the order of items in both lists. This means that the object in List<T> must occupy the same position as its corresponding ID in List<long>, for example, the object with ID 1 in docs should be at index 1.

To achieve this sorting without modifying List<T> you can use LINQ as follows:

<code class="language-csharp">docs = docs.OrderBy(d => docIds.IndexOf(d.Id)).ToList();</code>

This LINQ expression first uses IndexOf to determine the index of each object ID in docIds. It then uses this index as the sort key, effectively aligning the objects in List<T> with their IDs in List<long>.

The above is the detailed content of How to Sort a List of Objects Based on IDs from a Separate List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn