111,126
社区成员
发帖
与我相关
我的任务
分享
public class A
{
public int AID{get;set;}
public IList<B> BList{get;set;}
}
public class B
{
public int BID{get;set;}
public IList<C> CList{get;set;}
}
public class C
{
public int CID{get;set;}
}
static void Main(string[] args)
{
IList<A> aList = new List<A>();
aList.Add(new A { AID = 1, BList = new List<B>() { new B{BID=1}} });
aList.Add(new A { AID = 2, BList = new List<B>() { new B { BID = 2 } } });
EqualityComparer<A> eq = new EqualityComparer<A>();
//eq.ComparerString.Add("AID");
eq.ComparerString.Add("BList");
bool isExists = aList.Contains(new A { BList = new List<B>() { new B { BID = 1 } } }, eq);
Console.WriteLine(isExists);
}
然后 有个比较类
public class EqualityComparer<T> : IEqualityComparer<T>
{
/// <summary>
/// 需要比较的属性名称
/// </summary>
public IList<string> ComparerString
{
get;
set;
}
public EqualityComparer()
{
ComparerString = new List<string>();
}
public bool Equals(T a, T b)
{
if (object.ReferenceEquals(a, b))
return true;
if (object.ReferenceEquals(a, null) || object.ReferenceEquals(b, null))
return false;
if (ComparerString == null || ComparerString.Count <= 0)
{
bool isSame = false;
foreach (PropertyInfo p in a.GetType().GetProperties())
{
if (p.PropertyType.IsGenericType)
{
if (!IsListSame(p.GetValue(a, null), b.GetType().GetProperty(p.Name).GetValue(b, null)))
return false;
}
else
{
isSame = p.GetValue(a, null) == b.GetType().GetProperty(p.Name).GetValue(b, null);
if (!isSame)
return false;
}
}
return true;
}
else
{
foreach (string str in ComparerString)
{
if (a.GetType().GetProperty(str).PropertyType.IsGenericType)
{
if (!IsListSame(a.GetType().GetProperty(str).GetValue(a, null), b.GetType().GetProperty(str).GetValue(b, null)))
return false;
}
else
{
if (a.GetType().GetProperty(str).GetValue(a, null) != b.GetType().GetProperty(str).GetValue(b, null))
return false;
}
}
return true;
}
}
private bool IsListSame(object oa,object ob)////这个比较IList 怎么比较 不知道类型 怎么弄?
{
IList<object> a=new List<object>();
IList<object> b = new List<object>();
foreach (object suba in a)
{
if (b.Contains(suba))
return true;
}
return false;
}
public int GetHashCode(T o)
{
if (object.ReferenceEquals(o, null))
return 0;
int hashResult = 0;
if (ComparerString == null || ComparerString.Count <= 0)
{
foreach (PropertyInfo p in o.GetType().GetProperties())
{
hashResult = hashResult ^ (p.GetValue(o, null) != null ? p.GetValue(o, null).GetHashCode() : 0);
}
return hashResult;
}
else
{
foreach (string str in ComparerString)
{
hashResult = hashResult ^ (o.GetType().GetProperty(str).GetValue(o, null) != null ? o.GetType().GetProperty(str).GetValue(o, null).GetHashCode() : 0);
}
return hashResult;
}
}
}
foreach (PropertyInfo p in a.GetType().GetProperties())
{
var obj = p.GetValue(a, null);
if (obj is IList)
{
//转换为IList比较内部项
IList lobj = (IList)obj;
for (int i = lobj.Count - 1; i >= 0; i--)
{
var item = lobj[i];//得到内部项,怎么比较自己写
}
}
else
{
//常规比较
}