Why Linq Distinct() does not work for my ConsultantList?

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)
       .Select(c =>
             new ConsultantItemDTO
                EmployeeId = c.ConsultantId,
                EmployeeName = c.Employee.Firstname + " " + c.Employee.Lastname

Here is the entire method:

Get Project Method

One Answer

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

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP