LINQ's
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:
List<Person> distinctPeople = allPeople .GroupBy(p => p.Id) .Select(g => g.First()) .ToList();
If you need to group according to multiple attributes, you can use anonymous type:
<事> Note:
Some query providers may need to use
List<Person> distinctPeople = allPeople .GroupBy(p => new { p.Id, p.FavoriteColor }) .Select(g => g.First()) .ToList();
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/7dd21654ce1c39EC763219E71F11FirstOrDefault()
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!