去重
IEqualityComparer 实现 IEqualityComparer接口
public class ProductIdComparer
: IEqualityComparer
<Product
>
{
public bool
Equals(Product x
, Product y
)
{
if (x
== null
)
return y
== null
;
return x
.Id
== y
.Id
;
}
public
int GetHashCode(Product obj
)
{
if (obj
== null
)
return 0;
return obj
.Id
.GetHashCode();
}
}
GroupBy 使用GroupBy方式去重
List
<Product
> distinctProduct
= allProduct
.GroupBy(p
=> new
{p
.Id
, p
.Name
} )
.Select(g
=> g
.First())
.ToList();
Distinct 对需要Distinct的字段进行分组,取组内的第一条记录这样结果就是Distinct的数据了。
方法的使用
针对ID,和Name进行Distinct
var query
= allProduct
.DistinctBy(p
=> new
{ p
.Id
, p
.Name
});
仅仅针对ID进行distinct:
var query
= allProduct
.DistinctBy(p
=> p
.Id
);
hash 去重
public
static IEnumerable
<TSource
> DistinctBy
<TSource
, TKey
> (this IEnumerable
<TSource
> source
, Func
<TSource
, TKey
> keySelector
)
{
HashSet
<TKey
> seenKeys
= new HashSet
<TKey
>();
foreach
(TSource element in source
)
{
if (seenKeys
.Add(keySelector(element
)))
{
yield
return element
;
}
}
}
Linq groupby
分组合并查询 查询表达式 … group… by…
var groupPlanDetails
= from projectPlanDetail in planDetails
group projectPlanDetail by projectPlanDetail
.ProjectId
;
var periPlanDetails
=groupPlanDetails
.Select(t
=> new
PeriPlanDetailInfo(){
EmpIds
= t
.FirstOrDefault().EmpIds
,
Patrollers
= t
.FirstOrDefault().Patrollers
,
PeriStartTime
= t
.FirstOrDefault().PeriStartTime
,
PeriEndTime
= t
.FirstOrDefault().PeriEndTime
,
ProjectId
= t
.FirstOrDefault().ProjectId
,
ProjectName
= t
.FirstOrDefault().ProjectName
,
Type
= t
.FirstOrDefault().Type
,
State
= t
.Where(s
=> s
.State
==2).Count()>0?2: (t
.Where(s
=> s
.State
== 0).Count() == 0 ? 1 : 0),
Count
= t
.Sum(s
=>s
.Count
),
PeriFrequency
= t
.Sum(s
=>s
.PeriFrequency
),
});
Linq数据分组官方文档