如何通过List<>中的属性值删除重复项
本文关键字:删除 属性 List 何通过 | 更新日期: 2023-09-27 18:14:38
有人能帮我把这个Linq查询告诉我如何拔出不同的产品名称
List<StatePlan> planTypes = (from ppt in context.PlanPlanTypes
join pt in context.PlanTypes on ppt.PlanTypeRowID equals pt.PlanTypeRowID
join ppts in context.PlanPlanTypeStates on ppt.PlanPlanTypeRowID equals ppts.PlanPlanTypeRowID
join p in context.Plans on ppt.PlanRowID equals p.PlanRowID
where ppts.StateCode == stateCode
where p.IsActive == true
select new StatePlan
{
PlanID = p.PlanRowID,
StateCode = stateCode,
Name = p.Name,
Description = p.Description,
Disclaimer = p.Disclaimer,
Sequence = p.DisplaySequence,
//Rates = GetRates(p.PlanRowID),
//Types = GetPlanTypes(p.PlanRowID, stateCode)
}).ToList();
return planTypes;
我不确定我是否正确理解了这个问题,但是如果您想要具有特定不同字段的项,您可以使用groupby+first:
seq.GroupBy(item=>item.Name).Select(group=>group.First())
你也可以使用投影相等比较器,但我认为这有点难看。对我来说,使用Distinct
意味着你不关心你得到的是哪个等价物。而groupby+first则明确表示需要第一个。
GroupBy还允许您在Select
子句中收集其他信息,例如,有多少项具有这样的名称。
如果只需要不同的名称而不需要相关联的项,请组合select和distinct:
seq.Select(item=>item.Name).Distinct()
先分组再取第一个
List<StatePlan> planTypes = (from ppt in context.PlanPlanTypes
join pt in context.PlanTypes on ppt.PlanTypeRowID equals pt.PlanTypeRowID
join ppts in context.PlanPlanTypeStates on ppt.PlanPlanTypeRowID equals ppts.PlanPlanTypeRowID
join p in context.Plans on ppt.PlanRowID equals p.PlanRowID
where ppts.StateCode == stateCode
where p.IsActive == true
select new StatePlan
{
PlanID = p.PlanRowID,
StateCode = stateCode,
Name = p.Name,
Description = p.Description,
Disclaimer = p.Disclaimer,
Sequence = p.DisplaySequence,
//Rates = GetRates(p.PlanRowID),
//Types = GetPlanTypes(p.PlanRowID, stateCode)
})
.GroupBy(g => g.Name)
.Select(s => s.First())
.ToList();
return planTypes;
planTypes.Select(pt=>pt.Name).Distinct();
您可以调用Distinct
并为StatePlan
提供等价比较器
假设产品名称是planTypes
列表中的Name
属性,并且它是一个字符串:
List<string> productNames = planTypes.Select(t => t.Name).Distinct().ToList();