Home > Backend Development > C++ > How Can I Group Objects by a Common Property Using LINQ?

How Can I Group Objects by a Common Property Using LINQ?

Mary-Kate Olsen
Release: 2025-01-13 11:50:46
Original
535 people have browsed it

How Can I Group Objects by a Common Property Using LINQ?

Group objects by common properties using LINQ

This example demonstrates how to group a list of objects based on shared properties. Using LINQ, we can achieve this using the GroupBy and Select methods.

The GroupBy method creates a collection of key-value pairs, where the keys represent unique values ​​for the specified attributes. In this example, we group by the GroupID attribute. The resulting output will be a collection of key-value pairs, where the key is the GroupID and the value is an enumeration of all User objects that share the same GroupID.

To convert these key-value pairs into a list of grouped lists, we apply the Select method. In the Select clause, we use the ToList method to convert the value part of each key-value pair (which is an enumeration of User objects) into a list.

Putting everything together, here is the LINQ query to achieve the desired grouping:

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

The final groupedCustomerList will be a list of lists, where each inner list contains User objects grouped by their GroupID. This structure allows you to easily access and manipulate grouped data as needed.

The above is the detailed content of How Can I Group Objects by a Common Property 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