C# 集合中按照字段去除重复

创建去重方法

public static IEnumerable<T> DistinctBy<T, TResult>(this IEnumerable<T> source, Func<T, TResult> where)
{
    HashSet<TResult> hashSetData = new HashSet<TResult>();
    foreach (T item in source)
    {
        if (hashSetData.Add(where(item)))
        {
            yield return item;
        }
    }
}

调用实例

String list=JSON字符串;

var projectList = JsonConvert.DeserializeObject<List<ProjectModel>>(list);

//根据ProjectCD去重,返回去重后的数据
var tmpSSlIST = projectList.DistinctBy(item => new { item.ProjectCD});

IEnumerable 

什么是IEnumerable?

IEnumerable及IEnumerable的泛型版本IEnumerable<T>是一个接口,它只含有一个方法GetEnumerator。

Enumerable这个静态类型含有很多扩展方法,其扩展的目标是IEnumerable<T>。

实现了这个接口的类可以使用Foreach关键字进行迭代(迭代的意思是对于一个集合,可以逐一取出元素并遍历之)。实现这个接口必须实现方法GetEnumerator。

IEnumerable: 暴露一个IEnumerator,支持在普通集合中的遍历。

IEnumerable<T>:继承自IEnumerable,暴露一个IEnumerator<T>,支持在泛型集合中遍历。

Func<TResult> 委托

封装一个方法,该方法不具有参数,且返回由 TResult 参数指定的类型的值。

public delegate TResult Func<out TResult>()

返回值

Type: TResult

此委托封装的方法的返回值。

类型参数

out TResult

此委托封装的方法的返回值类型。

可以使用此委托来表示的方法,而无需显式声明自定义的委托作为参数进行传递。 封装的方法必须对应于此委托定义的方法签名。 这意味着,封装的方法必须具有任何参数,并且必须返回一个值。

猜你喜欢

转载自blog.csdn.net/weixin_41392824/article/details/82492973
今日推荐