有人可以帮我解决这个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;
答案 0 :(得分:3)
我不确定我是否正确理解了这个问题,但如果您想要具有特定字段的项目,则可以先使用groupby +:
seq.GroupBy(item=>item.Name).Select(group=>group.First())
您也可以使用投影相等比较器,但我认为有点难看。对我来说使用Distinct
意味着你不关心你得到哪些等价物品。而groupby +首先明确表明你想要第一个。
GroupBy还允许您在Select
子句中收集其他信息,例如,有多少具有此名称的项目。
如果您只想要不带关联项的不同名称,请将select和distinct结合起来:
seq.Select(item=>item.Name).Distinct()
答案 1 :(得分:1)
planTypes.Select(pt=>pt.Name).Distinct();
答案 2 :(得分:1)
先将它分组,然后再进行第一次
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;
答案 3 :(得分:0)
您可以调用Distinct
并为StatePlan
答案 4 :(得分:0)
假设产品名称是Name
列表中的planTypes
属性,并且它是一个字符串:
List<string> productNames = planTypes.Select(t => t.Name).Distinct().ToList();