Search Results for

    Show / Hide Table of Contents

    Class PropertyComparer<T, P>

    Implements IEqualityComparer<T> for the specified type T comparing the specified property

    Inheritance
    object
    PropertyComparer<T, P>
    Implements
    IEqualityComparer<T>
    Inherited Members
    object.GetType()
    object.MemberwiseClone()
    object.ToString()
    object.Equals(object)
    object.Equals(object, object)
    object.ReferenceEquals(object, object)
    object.GetHashCode()
    Namespace: LemonEdge.Utils
    Assembly: LemonEdge.Utils.dll
    Syntax
    public class PropertyComparer<T, P> : IEqualityComparer<T>
    Type Parameters
    Name Description
    T

    The type to compare equality for

    P

    The return type of the property to use to compare equality on

    Remarks

    This is useful in Linq functionality where you want distinct lists of items that have certain property values. For example:

    public class MyItem 
    {
        public int Value { get; set; }
        public string Group { get; set; }
    
        public override string ToString() => Value.ToString();
    }
    
    private IEnumerable<MyItem> GetFirstItemOfEachGroup()
    {
        var items = new List<MyItem>() { new MyItem { Group = "1", Value = 1 }, new MyItem { Group = "1", Value = 2 }, new MyItem { Group = "2", Value = 3 } };
        return items.Distinct(PropertyComparer<MyItem, string>.Create(x => x.Group));
    }

    Will return:

    1,3

    Constructors

    PropertyComparer()

    Declaration
    public PropertyComparer()

    Methods

    Create(Func<T, P>)

    Creates a new PropertyComparer that can compare two instances of type T and determine if their property values are equal

    Declaration
    public static PropertyComparer<T, P> Create(Func<T, P> prop)
    Parameters
    Type Name Description
    Func<T, P> prop

    A function that return the value of a specific property given an instance of type T

    Returns
    Type Description
    PropertyComparer<T, P>

    A new PropertyComparer that can compare if instances have the same property value or not

    Equals(T, T)

    Declaration
    public bool Equals(T x, T y)
    Parameters
    Type Name Description
    T x
    T y
    Returns
    Type Description
    bool

    GetHashCode(T)

    Declaration
    public int GetHashCode(T obj)
    Parameters
    Type Name Description
    T obj
    Returns
    Type Description
    int

    Implements

    IEqualityComparer<T>

    Extension Methods

    LinqExtensions.AsArray<T>(T)
    LinqExtensions.ToArrayOfOne<T>(T)
    LinqExtensions.ToListOfOne<T>(T)
    MiscExtensions.SetIfNotEqual<T, TP>(T, Expression<Func<T, TP>>, TP)
    WeakReferenceExtensions.WeakReference(object)
    SQLExtensions.ToSQLValue(object, bool)
    ReflectionExtensions.ClearEventInvocations(object, string)
    StringExtensions.ToCSVFormatString(object, Type)
    In this article
    Back to top © LemonEdge Technologies. All rights reserved.