Skip to content

Instantly share code, notes, and snippets.

@thdotnet
Created November 24, 2016 11:17
Show Gist options
  • Save thdotnet/8e0a79be50ce4eb931fcef9c33340707 to your computer and use it in GitHub Desktop.
Save thdotnet/8e0a79be50ce4eb931fcef9c33340707 to your computer and use it in GitHub Desktop.
Linq Distinct By implementation
using System;
using System.Collections.Generic;
using System.Linq;
namespace Testes
{
class Program
{
static void Main(string[] args)
{
var list = new List<Foo> {
new Foo{ Id = 1, Text = "Foo 1" },
new Foo{ Id = 2, Text = "Foo 2" },
new Foo{ Id = 1, Text = "Foo 1" },
};
var distinctList = list.Distinct();
Console.WriteLine(distinctList.Count());
Console.Read();
distinctList = list.DistinctBy(x => x.Id);
Console.WriteLine(distinctList.Count());
Console.Read();
}
}
public class Foo
{
public int Id { get; set; }
public string Text { get; set; }
}
static class LinqExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> predicate)
{
if (source == null) throw new ArgumentException("source not defined");
if (predicate == null) throw new ArgumentException("predicate not defined");
if (source != null && source.Count() > 0)
{
return source.GroupBy(predicate)
.Select(group => group.First())
.ToList();
}
return source;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment