Home >Backend Development >C++ >How to Use LINQ to Get Distinct Objects Based on Specific Properties?

How to Use LINQ to Get Distinct Objects Based on Specific Properties?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-02 09:01:10211browse

How to Use LINQ to Get Distinct Objects Based on Specific Properties?

Using the specific attribute of the linq to the object list, the application is used

LINQ's method allows you to eliminate repetitive elements in the set. However, when processing a list of complex objects, which attributes are required for uniqueness.

Solution: Distinct()

For this reason, you can group the object according to the required attributes and select the first element from each group. This will provide you with a list, the object in this list is unique for the specified attribute. Example:

Consider Person object with ID and name attributes:

To get different personnel lists based on ID attributes:

This will generate a list containing only Person1 and Person3.
<code>Person1:Id=1,Name="Test1"
Person2:Id=1,Name="Test1"
Person3:Id=2,Name="Test2"</code>

Multiple attributes:

<code class="language-csharp">List<Person> distinctPeople = allPeople
  .GroupBy(p => p.Id)
  .Select(g => g.First())
  .ToList();</code>

If you need to group according to multiple attributes, you can use anonymous type:

Note:

Some query providers may need to use
<code class="language-csharp">List<Person> distinctPeople = allPeople
  .GroupBy(p => new { p.Id, p.FavoriteColor })
  .Select(g => g.First())
  .ToList();</code>
instead of

to ensure that each group has at least one element. For compatible methods compatible with Linq to Entities (EF Core) (before the 6th version), please refer to this reply:

https://www.php.cn/link/7dd21654ce1c39EC763219E71F11
  • FirstOrDefault() First()

The above is the detailed content of How to Use LINQ to Get Distinct Objects Based on Specific Properties?. 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