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);
5
  • Where does value1 and value2 come? Commented Apr 2, 2014 at 13:52
  • Does this help: stackoverflow.com/questions/1300088/distinct-with-lambda?rq=1 Commented Apr 2, 2014 at 13:55
  • Ah, reading that question, those are the values to compare to find the distinct. Commented Apr 2, 2014 at 14:02
  • 1
    you must have a IEqualityComparer class in order to Distinct elements. Commented Apr 2, 2014 at 14:51
  • @Patrick It works! Problem solved ! Commented Apr 2, 2014 at 14:56

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.