Home > Backend Development > C++ > How Can LINQ Group a List of Objects into Nested Lists?

How Can LINQ Group a List of Objects into Nested Lists?

Susan Sarandon
Release: 2025-01-13 11:35:43
Original
618 people have browsed it

How Can LINQ Group a List of Objects into Nested Lists?

Group list of objects into nested lists using LINQ

Efficient data organization is crucial in the field of programming. LINQ provides a powerful mechanism for grouping objects based on specific conditions. This article will solve a common problem: grouping a list of objects into a new list containing nested lists.

Consider the following class definition:

<code>public class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public int GroupID { get; set; }
}</code>
Copy after login

In order to group users based on their GroupID, we can utilize the following code:

<code>var groupedCustomerList = userList
    .GroupBy(u => u.GroupID)
    .Select(grp => grp.ToList())
    .ToList();</code>
Copy after login

Code interpretation:

  1. GroupBy: This clause divides the original user list into multiple groups based on the GroupID attribute.
  2. Select: It then converts each result (i.e. a set of users with the same GroupID) into a list of users.
  3. ToList: Finally, the result is converted into a new list of nested lists, each nested list containing users from the same group.

This LINQ expression cleverly groups the original list of users by GroupID, presenting them in an organized manner. Each nested list in the final result represents a group of users sharing the same GroupID.

The above is the detailed content of How Can LINQ Group a List of Objects into Nested Lists?. 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