对于类型的对比,linq原来的对比是区分不了的。
对两个list进行查询交集方法。交集,并集的函数是直接用Linq的,这里不再写。
List<T> intersectList = queryList.AsQueryable().Intersect(sqlList, new ListEquality<T>()).ToList();
public class ListEquality<T> : IEqualityComparer<T> where T : new()
{ PropertyInfo[] propertys = typeof(T).GetProperties().Where(p => p.Name != "ParamInfo").Where(p => p.Name != "State").ToArray(); public bool Equals(T x, T y)
{
foreach (var pe in propertys)
{
object o_x = pe.GetValue(x, null);
object o_y = pe.GetValue(y, null);
if (!object.Equals(o_x, o_y))
{
return false;
}
}
return true;
} public int GetHashCode(T obj)
{
if (obj == null)
{
return ;
}
else
{
return obj.ToString().GetHashCode();
}
}
}
上面的代码明显是根据排除字段来对比的。如果你不想根据字段对比,那就不要排除。
通过主键属性来对比仅仅是主键的类
public class ListKeyEquality<T> : IEqualityComparer<T> where T : new()
{ PropertyInfo[] propertys = typeof(T).GetProperties().Where(p => p.Name != "ParamInfo").Where(p => p.Name != "State").ToArray();
public bool Equals(T x, T y)
{
foreach (var pe in propertys)
{
object[] allAttributes = pe.GetCustomAttributes(false);
if (allAttributes.Count() == )
{
continue;
}
if ((allAttributes.FirstOrDefault() as GrantAttribute).IsKey)
{
object o_x = pe.GetValue(x, null);
object o_y = pe.GetValue(y, null);
if (!object.Equals(o_x, o_y))
{
return false;
}
} }
return true;
} public int GetHashCode(T obj)
{
if (obj == null)
{
return ;
}
else
{
return obj.ToString().GetHashCode();
}
}
}
public class GrantAttribute : Attribute
{
/// <summary>
/// 是否xml类型
/// </summary>
public bool CheckXml { get; set; }
/// <summary>
/// 是否主键
/// </summary>
public bool IsKey { get; set; }
}
类的主键属性调用也是很简单
public class OrderInfo
{
/// <summary>
/// 本系统订单ID
/// </summary>
[Grant(IsKey = true)]
public Guid OrderId { get; set; }
}