Home > Backend Development > C++ > How to Sort a List Based on the Order of Identifiers in Another List Using LINQ?

How to Sort a List Based on the Order of Identifiers in Another List Using LINQ?

Patricia Arquette
Release: 2025-01-19 12:12:11
Original
241 people have browsed it

How to Sort a List Based on the Order of Identifiers in Another List Using LINQ?

Sorting a List Based on Identifiers from Another List Using LINQ

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 };
Copy after login

You also have a list of items represented by the IDs in docIds:

List<T> docs = GetDocsFromDb(...);
Copy after login

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();
Copy after login

Explanation:

  1. OrderBy(d => docIds.IndexOf(d.Id)): This lambda expression specifies the sorting criterion. It retrieves the index of the item's ID in the docIds list, effectively sorting the docs list based on the position of its IDs in docIds.
  2. ToList(): This converts the sorted result into a new list, preserving the sorted order.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template