LINQ的Distinct总结
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)
return 0;
else
return propertyValue.GetHashCode();
}
#endregion
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示