[英]Substitute IEquatable interface when doing distinct() on a lambda
I have this class which implements the IEquatable<T>
interface我有这个实现
IEquatable<T>
接口的类
public class ArticleDescriptionDetails : IEquatable<ArticleDescriptionDetails>
{
public string Code { get; set; }
public string Value { get; set; }
public bool Hidden { get; set; }
public bool Equals(ArticleDescriptionDetails other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Code == other.Code;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((ArticleDescriptionDetails) obj);
}
public override int GetHashCode() => ((Code != null ? Code.GetHashCode() : 0) * 397) ^ Hidden.GetHashCode();
public static bool operator ==(ArticleDescriptionDetails left, ArticleDescriptionDetails right) => Equals(left, right);
public static bool operator !=(ArticleDescriptionDetails left, ArticleDescriptionDetails right) => !Equals(left, right);
}
I need this beacuse I'm tring to return an IEquatable<ArticleDescriptionDetails>
in this way:我需要这个,因为我想以这种方式返回
IEquatable<ArticleDescriptionDetails>
:
return result.OrderBy(x => x.Code).ThenBy(y => y.Hidden).Distinct();
Is there a way to do the same thing without using the IEquatable<T>
interface?有没有办法在不使用
IEquatable<T>
接口的情况下做同样的事情?
You could use a DistinctBy method and do您可以使用 DistinctBy 方法并执行
return result.OrderBy(x => x.Code).ThenBy(y => y.Hidden).DistinctBy(z => z.Code);
But the DistinctBy method doesn't exist in linq but you can find it in the morelinq package https://www.nuget.org/packages/MoreLinq.Source.MoreEnumerable.DistinctBy/但是 linq 中不存在 DistinctBy 方法,但您可以在 morelinq 包https://www.nuget.org/packages/MoreLinq.Source.MoreEnumerable.DistinctBy/ 中找到它
But it's also easy to code your own version of the method : You first need to define an IEqualityComparer但是编写自己的方法版本也很容易:首先需要定义一个 IEqualityComparer
public class KeyEqualityComparer<T, K> : IEqualityComparer<T>
{
private readonly Func<T, K> selector;
public KeyEqualityComparer(Func<T, K> keySelector)
{
selector = keySelector;
}
public bool Equals(T x, T y)
{
return selector(x).Equals(selector(y));
}
public int GetHashCode(T obj)
{
return selector(obj).GetHashCode();
}
}
And the you can use this IEqualityComparer in the Distinct method :您可以在 Distinct 方法中使用此 IEqualityComparer:
public static IEnumerable<T> DistinctBy<T, K>(this IEnumerable<T> list, Func<T, K> keySelector)
{
var equalityComparer = new KeyEqualityComparer<T, K>(keySelector);
return list.Distinct(equalityComparer);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.