Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove doubles from structs array

Tags:

c#

linq

distinct

I know 2 ways to remove doubles from an array of objects that support explicit comparing:

  1. Using HashSet constructor and
  2. Using LINQ's Distinct().

How to remove doubles from array of structs, comparing array members by a single field only? In other words, how to write the predicate, that could be used by Distinct().

Regards,

like image 848
noober Avatar asked Dec 21 '22 19:12

noober


1 Answers

Well, you could implement IEqualityComparer<T> to pick out that field and use that for equality testing and hashing... or you could use DistinctBy which is in MoreLINQ.

Of course, you don't have to take a dependency on MoreLINQ really - you can implement it very simply:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector)
{
    // TODO: Implement null argument checking :)

    HashSet<TKey> keys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (knownKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}
like image 170
Jon Skeet Avatar answered Jan 13 '23 10:01

Jon Skeet