C# List之distinct用法

论坛 期权论坛 脚本     
匿名技术用户   2020-12-30 06:23   535   0

创建继承IEqualityComparer接口的类,这个是通用的,复制直接使用,不用改任何东西

//创建list<T>方法distinct比较器
public delegate bool CompareDelegate<T>(T x, T y);
public class Compare<T> : IEqualityComparer<T>
{
private CompareDelegate<T> _compare;
public Compare(CompareDelegate<T> d)
{
this._compare = d;
}

public bool Equals(T x, T y)
{
if (_compare != null)
{
return this._compare(x, y);
}
else
{
return false;
}
}

public int GetHashCode(T obj)
{
return obj.ToString().GetHashCode();
}
}

调用方法(Comment是list里面装的对象):

list.Distinct(new Compare<Comment>((x, y) => (x != null && y != null) &&(x.UserID == y.UserID))).ToList();


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP