You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.3 KiB
53 lines
1.3 KiB
3 years ago
|
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
|
||
|
namespace EC.Utils
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 泛型Distinct比较
|
||
|
/// Data.Distinct(new ExtList<T>("字段")).ToList();
|
||
|
/// 版 本:V3.0.0
|
||
|
/// 版 权:EasyCode
|
||
|
/// 作 者:LXC
|
||
|
/// </summary>
|
||
|
/// <typeparam name="T"></typeparam>
|
||
|
public class ExtList<T> : IEqualityComparer<T> where T : class, new()
|
||
|
{
|
||
|
private string[] comparintFiledName = { };
|
||
|
|
||
|
public ExtList(params string[] comparintFiledName)
|
||
|
{
|
||
|
this.comparintFiledName = comparintFiledName;
|
||
|
}
|
||
|
|
||
|
bool IEqualityComparer<T>.Equals(T x, T y)
|
||
|
{
|
||
|
if (x == null && y == null)
|
||
|
{
|
||
|
return false;
|
||
|
}
|
||
|
if (comparintFiledName.Length == 0)
|
||
|
{
|
||
|
return x.Equals(y);
|
||
|
}
|
||
|
bool result = true;
|
||
|
var typeX = x.GetType();//获取类型
|
||
|
var typeY = y.GetType();
|
||
|
foreach (var filedName in comparintFiledName)
|
||
|
{
|
||
|
var xPropertyInfo = (from p in typeX.GetProperties() where p.Name.Equals(filedName) select p).FirstOrDefault();
|
||
|
var yPropertyInfo = (from p in typeY.GetProperties() where p.Name.Equals(filedName) select p).FirstOrDefault();
|
||
|
|
||
|
result = result
|
||
|
&& xPropertyInfo != null && yPropertyInfo != null
|
||
|
&& xPropertyInfo.GetValue(x, null).ToString().Equals(yPropertyInfo.GetValue(y, null));
|
||
|
}
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
int IEqualityComparer<T>.GetHashCode(T obj)
|
||
|
{
|
||
|
return obj.ToString().GetHashCode();
|
||
|
}
|
||
|
}
|
||
|
}
|