我使用T-SQL / SQL Server相当新,我不确定如何使用Linq获得所需的结果。
从下面的代码我得到以下结果:
from com in Complaints
join pro in Projects on com.ProjectId equals pro.ProjectId
join cont in Contacts on com.SubContractorContactId equals cont.ContactId
join cont2 in Contacts on com.OccupantContactId equals cont2.ContactId
where com.EmailStatusId == null
select new
{
pro.ProjectName,
com.ComplaintId,
com.ComplaintName,
SubContractorName = cont.FirstName,
SubContractorEmail = cont.Email,
com.DueDate,
OccupantName = cont2.FirstName,
OccupantPhone = cont2.Phone,
OccupantEmail = cont2.Email
}
我希望结果返回一个独立的项目,其中列出了每个投诉。此外,我希望在删除重复内容时对投诉中的每个联系人进行分组。因此,我希望的结果将是每个项目的一行,然后是项目内的每个投诉,以及每个投诉联系人。
为了帮助您了解我已创建此大纲。
Projects
- Lake Road Construction
- Complaints
- Foundation Cracks: ComplaintId 1, DueDate
- Contacts
- SubContractor
- Carlo
- CarloARosner@inbound.plus
- Occupant
- William
- WilliamSSommerfield@inbound.plus
- 616-846-0467
- Drywall: ComplaintId 2, DueDate
- Contacts
- SubContractor
* No SubContractor needed since the previous complaint has the same SubContractor.
- Occupant
- Keesha
- KeeshaCWhitlock@inbound.plus
- 661-205-2018
- Jennifer Lane Renovation
- Complaints
- Light Fixture: ComplaintId 3, DueDate
- Contacts
- SubContractor
- Ardith
- ArdithGMast@inbound.plus
- Occupant
- Olivia
- OliviaEFournier@inbound.plus
- 210-530-5281
- Plumbing: ComplaintId 4, DueDate
- Contacts
* Contacts have already been collected from the other complaint.
从我所读过的内容来看,我认为我需要使用" group by new {}"或使用UNION。但是,我不确定我需要进入的方向。任何帮助都将不胜感激。
答案 0 :(得分:2)
这应该根据ProjectName对数据进行分组。结果是具有Project
属性和Complaints
属性的匿名对象列表。 Complaints
媒体资源中的每个项目都有CompId
和Contact
属性
var groupedResults = (from co in Complaints
join p in Projects on co.ProjectId equals p.ProjectId
join cont in Contacts on co.SubContractorContactId equals cont.ContactId
join cont2 in Contacts on co.OccupanttContactId equals cont2.ContactId
select new
{
ProjecttName = p.Name,
ComplaintId = co.Id,
SubContractorName = cont.FirstName,
OccupantName = cont2.FirstName
// Fill the other properties here please
}
).GroupBy(k => k.ProjecttName, i => i, (x, b) => new
{
Project=x,
Complaints =b.Select(d=> new
{
CompId=d.ComplaintId,
Contacts=new { SubContr=d.SubContractorName, Occupant = d.OccupantName}
})
}).ToList();