Use Linq's distinct () method to obtain the unique object
LINQ (Language Integration inquiry) provides a powerful tool
to filter and retrieve unique elements from the collection. However, when the attributes of the object are not simple, the use of may be tricky. Distinct()
Distinct()
Use differentin ()
To use on the attribute of the object, you need to group the object based on these attributes, and then select a unique representative from each group. This can be implemented using Linq's and
methods.
Distinct()
Example: Distance based on ID attribute GroupBy
Select
To obtain a list of the unique Person object according to the ID attribute, you can use the following code:
This code first groups the Person object according to its ID attribute to create a group set. Each group contains Person objects with the same ID. Then use the method to select the first Person object from each group, and effectively provide a unique list of Person objects based on the ID attribute.
<code>Person1:Id=1,Name="Test1" Person2:Id=1,Name="Test1" Person3:Id=2,Name="Test2"</code>
DISTINCT
<code class="language-csharp">List<Person> distinctPeople = allPeople .GroupBy(p => p.Id) .Select(g => g.First()) .ToList();</code>
You can also use Select
by defining the composite key on multiple attributes. For example, to obtain the unique Person object list based on ID and favoritecolor attributes, you can use the following code:
Note:
Please note that some query providers may not be able to analyze each group must include at least one element. In this case, Distinct()
may be a more suitable method. In addition, the previous version of EF Core 6 needs a little different ways. For details, see the Stackoverflow answer provided. (It is assumed that the original text refers to Stackoverflow answers. If not, you can delete this sentence)
The above is the detailed content of How Can I Use LINQ's Distinct() Method to Get Unique Objects Based on Specific Properties?. For more information, please follow other related articles on the PHP Chinese website!