您好我正在尝试使用DB中的不同行绑定gridview。我希望在JobID列上实现distict。请帮忙
using (ATPDataContext at = new ATPDataContext())
{
var qryPartnerJobs = (from pj in at.jobs
join jq in at.job_quotes on pj.JobID equals jq.JobID
join u in at.users on jq.TradeUserID equals u.UserID
where pj.IsApproved == true
select new
{
JobID = pj.JobID,
FirstName = u.FirstName,
ServiceName = pj.service.ServiceName,
ServiceTypeName = pj.service_type.ServiceTypeName,
IsApproved = pj.IsApproved,
IsActive = pj.IsActive,
IsQuoted = pj.IsQuoted,
IsAssigned = pj.IsAssigned,
ApprovalDate = pj.ApprovalDate,
Description = pj.Description
}).Distinct();
gvPartnerJob.DataSource = qryPartnerJobs;
gvPartnerJob.DataBind();
}
答案 0 :(得分:0)
Distinct
接受EqualityComparer<T>
作为参数。您可以使用以下比较器实现所请求的功能:
public class JobComparer : EqualityComparer<Job>
{
public override bool Equals(Job x, Job y)
{
return x.JobID == y.JobID;
}
public override int GetHashCode(Job obj)
{
return obj.JobID.GetHashCode();
}
}
使用此比较器,只需在您的收藏中使用Distinct(new JobComparer())
。
答案 1 :(得分:0)
如果要在SQL中执行distinct,请使用GroupBy()
var qryPartnerJobs = (from pj in at.jobs
join jq in at.job_quotes on pj.JobID equals jq.JobID
join u in at.users on jq.TradeUserID equals u.UserID
where pj.IsApproved == true
select new
{
JobID = pj.JobID,
FirstName = u.FirstName,
ServiceName = pj.service.ServiceName,
ServiceTypeName = pj.service_type.ServiceTypeName,
IsApproved = pj.IsApproved,
IsActive = pj.IsActive,
IsQuoted = pj.IsQuoted,
IsAssigned = pj.IsAssigned,
ApprovalDate = pj.ApprovalDate,
Description = pj.Description
})
// get a group for each distinct jobId
.GroupBy(t => t.JobID)
// select the first entry from each group
.SelectMany(g => g.Take(1));
如果您希望在内存中执行不同的操作,可以使用Distinct()重载,它允许您传递IEqualityComparer。