list 去重擴展:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> keys = new HashSet<TKey>(); foreach (TSource element in source) if (keys.Add(keySelector(element))) yield return element; }
比較兩個集合
public static bool CompareType<T>(T oneT, T twoT) { bool result = true;//兩個類型作比較時使用,如果有不一樣的就false Type typeOne = oneT.GetType(); Type typeTwo = twoT.GetType(); //如果兩個T類型不一樣 就不作比較 if (!typeOne.Equals(typeTwo)) { return false; } PropertyInfo[] pisOne = typeOne.GetProperties(); //獲取所有公共屬性(Public) PropertyInfo[] pisTwo = typeTwo.GetProperties(); //如果長度爲0返回false if (pisOne.Length <= 0 || pisTwo.Length <= 0) { return false; } //如果長度不一樣,返回false if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; } //遍歷兩個T類型,遍歷屬性,並作比較 for (int i = 0; i < pisOne.Length; i++) { //獲取屬性名 string oneName = pisOne[i].Name; string twoName = pisTwo[i].Name; //獲取屬性的值 object oneValue = pisOne[i].GetValue(oneT, null); object twoValue = pisTwo[i].GetValue(twoT, null); //比較,只比較值類型 if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String"))) { if (oneName.Equals(twoName)) { if (oneValue == null) { if (twoValue != null) { result = false; break; //如果有不一樣的就退出循環 } } else if (oneValue != null) { if (twoValue != null) { if (!oneValue.Equals(twoValue)) { result = false; break; //如果有不一樣的就退出循環 } } else if (twoValue == null) { result = false; break; //如果有不一樣的就退出循環 } } } else { result = false; break; } } else { //如果對象中的屬性是實體類對象,遞歸遍歷比較 bool b = CompareType(oneValue, twoValue); if (!b) { result = b; break; } } } return result; }