Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DistinctBy not recognized as method

Tags:

c#

linq

Maybe i missing using ? (i have using System.Li). with Distinct no problem.

This is my command that i want to add DistinctBy

 List<Capture> list = db.MyObject.Where(x => x.prop == "Name").ToList();
like image 303
user2976232 Avatar asked Nov 10 '13 13:11

user2976232


2 Answers

You can add a extension method

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
    return items.GroupBy(property).Select(x => x.First());
}

and You can use it like

 List<Capture> list = db.MyObject.Where(x => x.prop == "Name")
                     .DistinctBy(y=> y.prop )
                     .ToList();

OR, You can use DistincyBy provided through MoreLinq.

like image 152
Satpal Avatar answered Oct 06 '22 15:10

Satpal


Another example:

public static class ExtensionMethods
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var seenKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }
}
like image 22
JoshYates1980 Avatar answered Oct 06 '22 15:10

JoshYates1980