List<T>的對比,List<T>
對於類型的對比,linq原來的對比是區分不了的。
對兩個list進行查詢交集方法。交集,並集的函數是直接用Linq的,這裡不再寫。
List<T> intersectList = queryList.AsQueryable().Intersect(sqlList, new ListEquality<T>()).ToList();
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017012017335629.gif)
![]()
1 public class ListEquality<T> : IEqualityComparer<T> where T : new()
2 {
3
4 PropertyInfo[] propertys = typeof(T).GetProperties().Where(p => p.Name != "ParamInfo").Where(p => p.Name != "State").ToArray();
5
6
7 public bool Equals(T x, T y)
8 {
9 foreach (var pe in propertys)
10 {
11 object o_x = pe.GetValue(x, null);
12 object o_y = pe.GetValue(y, null);
13 if (!object.Equals(o_x, o_y))
14 {
15 return false;
16 }
17 }
18 return true;
19 }
20
21 public int GetHashCode(T obj)
22 {
23 if (obj == null)
24 {
25 return 0;
26 }
27 else
28 {
29 return obj.ToString().GetHashCode();
30 }
31 }
32 }
View Code
上面的代碼明顯是根據排除字段來對比的。如果你不想根據字段對比,那就不要排除。
通過主鍵屬性來對比僅僅是主鍵的類
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017012017335629.gif)
![]()
1 public class ListKeyEquality<T> : IEqualityComparer<T> where T : new()
2 {
3
4 PropertyInfo[] propertys = typeof(T).GetProperties().Where(p => p.Name != "ParamInfo").Where(p => p.Name != "State").ToArray();
5 public bool Equals(T x, T y)
6 {
7 foreach (var pe in propertys)
8 {
9 object[] allAttributes = pe.GetCustomAttributes(false);
10 if (allAttributes.Count() == 0)
11 {
12 continue;
13 }
14 if ((allAttributes.FirstOrDefault() as GrantAttribute).IsKey)
15 {
16 object o_x = pe.GetValue(x, null);
17 object o_y = pe.GetValue(y, null);
18 if (!object.Equals(o_x, o_y))
19 {
20 return false;
21 }
22 }
23
24 }
25 return true;
26 }
27
28 public int GetHashCode(T obj)
29 {
30 if (obj == null)
31 {
32 return 0;
33 }
34 else
35 {
36 return obj.ToString().GetHashCode();
37 }
38 }
39 }
View Code
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017012017335629.gif)
![]()
1 public class GrantAttribute : Attribute
2 {
3 /// <summary>
4 /// 是否xml類型
5 /// </summary>
6 public bool CheckXml { get; set; }
7 /// <summary>
8 /// 是否主鍵
9 /// </summary>
10 public bool IsKey { get; set; }
11 }
View Code
類的主鍵屬性調用也是很簡單
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017012017335629.gif)
![]()
public class OrderInfo
{
/// <summary>
/// 本系統訂單ID
/// </summary>
[Grant(IsKey = true)]
public Guid OrderId { get; set; }
}
View Code