Class PropertyComparer<T, P>
Implements System.Collections.Generic.IEqualityComparer<T> for the specified type T
comparing the specified property
Inheritance
System.Object
PropertyComparer<T, P>
Implements
System.Collections.Generic.IEqualityComparer<T>
Inherited Members
System.Object.Equals(System.Object)
System.Object.Equals(System.Object, System.Object)
System.Object.GetHashCode()
System.Object.GetType()
System.Object.MemberwiseClone()
System.Object.ReferenceEquals(System.Object, System.Object)
System.Object.ToString()
Namespace: LemonEdge.Utils
Assembly: 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
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 |
---|---|---|
System.Func<T, P> | prop | A function that return the value of a specific property given an instance of type |
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 |
---|---|
System.Boolean |
GetHashCode(T)
Declaration
public int GetHashCode(T obj)
Parameters
Type | Name | Description |
---|---|---|
T | obj |
Returns
Type | Description |
---|---|
System.Int32 |
Implements
System.Collections.Generic.IEqualityComparer<T>