我想在此LINQ语句的四个字段中添加DistinctBy,但出现一些错误,其中不包含DistinctBy的定义。我需要导入一个类吗?
public IQueryable<TemplatesJoinAgent> GetTemplateAgentKeyDiseaseId(Guid? agentKey, Guid? diseaseId)
{
//Common part
var TemplatesJoinAgent = (from t in UnitOfWork.GetRepository<Template>().Get()
join r in UnitOfWork.GetRepository<Regimen>().Get() on t.Id equals r.TemplateId
join rp in UnitOfWork.GetRepository<RegimenPart>().Get() on r.Id equals rp.RegimenId
join re in UnitOfWork.GetRepository<RegimenEntry>().Get() on rp.Id equals re.RegimenPartId
join a in UnitOfWork.GetRepository<Agent>().Get() on re.AgentVersionKey equals a.VersionKey
where t.IsCurrentVersion && t.Status==7 && a.IsCurrentVersion
select new TemplatesJoinAgent
{
Template = t,
Agent = a
});
//Extra filters
if (agentKey != null)
{
TemplatesJoinAgent = TemplatesJoinAgent.Where(o => o.Agent.VersionKey == agentKey);
}
if (diseaseId != null)
{
TemplatesJoinAgent = TemplatesJoinAgent.Where(o => o.Template.ExternalDiseaseId == diseaseId);
}
TemplatesJoinAgent = TemplatesJoinAgent.DistinctBy(x => t.DiseaseName).ToList();
return TemplatesJoinAgent;
}
答案 0 :(得分:0)
正如其他人所提到的,DistinctBy
不是标准LINQ函数的一部分。但是,您可以通过实现自己的DistinctBy扩展来添加此功能。像这样的人可以完成这项工作:
public static class IEnumerableExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
var keys = new HashSet<TKey>();
foreach (TSource item in source)
{
if (keys.Add(selector(item)))
yield return item;
}
}
}