LINQ命名空間下的Distinct方法有兩個重載,一個是對TSource的Queryable可查詢結果集支援的,别一個是隻對T的IList,Enumerable結果集支援的
看一下,如果是傳回為iqueryable<T>結果集,隻能用distinct()預設的方法,
如果是List<T>,就可以根據自己定義好的比較原則,進行字段級的過濾了
例如,可以對Person類,進行ID,與Name的相等來确實整個對象是否與其它執行個體對象相等:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class PersonCompar : System.Collections.Generic.IEqualityComparer<Person>
public bool Equals(Person x, Person y)
{
if (x == null)
return y == null;
return x.ID == y.ID;
}
public int GetHashCode(Person obj)
if (obj == null)
return 0;
return obj.ID.GetHashCode();
如果一個list<person>的執行個體為
personList,那麼,它根據ID過濾的程式為
personList.Distinct(new PropertyComparer<Person>("ID")).ToList().ForEach(i => Console.WriteLine(i.ID + i.Name));
PropertyComparer.cs代碼如下
/// <summary>
/// 屬性比較器
/// </summary>
/// <typeparam name="T"></typeparam>
public class PropertyComparer<T> : IEqualityComparer<T>
private PropertyInfo _PropertyInfo;
/// <summary>
/// 通過propertyName 擷取PropertyInfo對象 /// </summary>
/// <param name="propertyName"></param>
public PropertyComparer(string propertyName)
_PropertyInfo = typeof(T).GetProperty(propertyName,
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
if (_PropertyInfo == null)
{
throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
propertyName, typeof(T)));
}
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
object xValue = _PropertyInfo.GetValue(x, null);
object yValue = _PropertyInfo.GetValue(y, null);
if (xValue == null)
return yValue == null;
return xValue.Equals(yValue);
public int GetHashCode(T obj)
object propertyValue = _PropertyInfo.GetValue(obj, null);
if (propertyValue == null)
else
return propertyValue.GetHashCode();
#endregion