Class PropertyComparer<T, P>
Implements IEqualityComparer<T> for the specified type T
comparing the
specified property
Implements
Inherited Members
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
|
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 |