ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods

DistinctBy

Extension method to distinct by specific property.

Source

/// <summary>
/// Extension method to distinct by specific property.
/// </summary>
/// <param name="keySelector">Function to pass object for distinct to work.</param>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

Example

public class Data
{
    public string Name {get;set;}
    public bool IsSuccess {get;set;}
}
			var data = new List<Data>
			{
			   new Data {Name = "Ahmer", IsSuccess=false},
			   new Data {Name = "Ahmer", IsSuccess=true},
			   new Data {Name = "Sohail", IsSuccess=false},
			   new Data {Name = "Shamsi", IsSuccess=true},
			   new Data {Name = "Ahmer", IsSuccess=false}
			};
			var distinctByName = data.DistinctBy(d=>d.Name);


			foreach(var name in distinctByName)
			{
				 Console.WriteLine(name.Name);
			}


/*
OUTPUT:
Ahmer
Sohail
Shamsi
*/

Author: Ahmer Sohail

Submitted on: 14 okt 2021

Language: csharp

Type: generic

Views: 3195