John Smith
John Smith

Reputation: 1793

making code reusable with extension method

I tried to create such extension method :

using System;
using System.Collections.Generic;
using System.Linq;

namespace CommonLibs.CommonClasses.Extensions
{
    public static class EnumerableExt
    {
        public static IEnumerable<T> DistinctBy<T>(this IEnumerable<T> collection, Func<T, object> keyGroup)
        {
            return from x in collection group x by keyGroup into grp select grp.First();
        }
    }
}

but if I want to use it like this :

public class PricingCoefficient
{
    public int Id { get; set; }
    public double FootageFrom { get; set; }
    public double? FootageTo { get; set; }
    public decimal? Coefficient { get; set; }
}

pricingCoefficients.DistinctBy(x => new { x.Coefficient, x.FootageFrom, x.FootageTo });

it gives me error:

Error 30 The type 'AnonymousType#1' cannot be used as type parameter 'TKey' in the generic type or method 'CommonLibs.CommonClasses.EnumerableExtensions.DistinctBy(System.Collections.Generic.IEnumerable, System.Func)'. There is no implicit reference conversion from 'AnonymousType#1' to 'System.IEquatable'.

Any idea how to make this an extension method?

thanks

Upvotes: 0

Views: 125

Answers (2)

I4V
I4V

Reputation: 35353

You need another type T2, a keyselector like Func<T, T2> keyGroup and call it as keyGroup(x)

public static IEnumerable<T> DistinctBy2<T,T2>(this IEnumerable<T> collection, Func<T, T2> keyGroup)
{
    return from x in collection group x by keyGroup(x) into grp select grp.First();
}

Upvotes: 2

King King
King King

Reputation: 63327

Try this:

public static IEnumerable<T> DistinctBy<T>(this IEnumerable<T> collection, 
                                           Func<T, object> keyGroup) {
    return from x in collection group x by keyGroup(x) into grp select grp.First();
}

NOTE: I couldn't reproduce your problem, using keyGroup (without (x) doesn't throw any exception, it's just wrong to produce the correct result of DistinctBy.

Upvotes: 0

Related Questions