2

I have an enumerable of objects for which I need to specify equality.

var values = list.Distinct();

Is there a way to use lambda expression in Enumerable.Distinct() or some equivalent workaround?

var values = list.Distinct((value1, value2) => value1.Id == value2.Id);
spaghettifunk
  • 1,936
  • 4
  • 24
  • 46
rcornu
  • 35
  • 5

2 Answers2

2

No, you cant. You can, in the way that @Hogan says in his answer (https://stackoverflow.com/a/22815177/806975)

Also, you can use Select before Distinct, if you want to make distinct for a specific field.

list.Select(x => x.Id).Distinct();

However, this will return only the selected value (Id).

Based on the question referred by @Patrick in his comment above (Distinct() with lambda?), and trying to add something to it, you can do an extension method to make what you want to do:

namespace MyProject.MyLinqExtensions
{
    public static class MyLinqExtensions
    {
        public static System.Collections.Generic.IEnumerable<TSource> DistinctBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> list, System.Func<TSource, TKey> expr)
        {
            return list.GroupBy(expr).Select(x => x.First());
        }
    }
}

Then, you can use it this way:

list.DistinctBy(x => x.Id)

Just remember to import the namespace in the class where you want to use it: using MyProject.MyLinqExtensions;

Community
  • 1
  • 1
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
2

You can but you need to create a class that implements IEqualityComparer. Then you use Enumerable.Distinct Method (IEnumerable, IEqualityComparer)

Hogan
  • 69,564
  • 10
  • 76
  • 117