Created
November 24, 2016 11:17
-
-
Save thdotnet/8e0a79be50ce4eb931fcef9c33340707 to your computer and use it in GitHub Desktop.
Linq Distinct By implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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