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!

Related Questions

Call parent class method (with this context) in child class

2  Asked on December 27, 2021 by rjoxford


Replace .(dot) inside number Java between two elements

2  Asked on December 27, 2021 by alex-danilov


Filtering an array of objects Vue

2  Asked on December 27, 2021 by graham-morby


Is there any good idea to ceil or floor datetime in python3?

2  Asked on December 27, 2021 by asknature


How do I use django’s Q with django taggit?

4  Asked on December 27, 2021 by shino


When to use UserPassesTestMixin vs PermissionRequiredMixin

2  Asked on December 27, 2021 by david-jay-brady


nuxt: pass data from server plugin to client

1  Asked on December 27, 2021


Am I Using JDBC Connection Pooling?

4  Asked on December 27, 2021 by ryandlf


Ask a Question

Get help from others!

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