Stack Overflow Asked by Karim Husein on November 19, 2020
I’ve tried to return distinct values in my ConsultantList, but it is still returning duplicates.
ConsultantList = p.ProjectExtensions
.SelectMany(pext => pext.Consultants)
.Distinct()
.Select(c =>
new ConsultantItemDTO
{
EmployeeId = c.ConsultantId,
EmployeeName = c.Employee.Firstname + " " + c.Employee.Lastname
}),
Here is the entire method:
In the documentation says:
If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable generic interface in the class.
Or you can extend the IEnumerable:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
Example of use:
.Select(p => p.Employee)
.DistinctBy(p => p.EmployeeId)
Answered by Wellington Júnior on November 19, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP